﻿///<jscompress sourcefile="VFG.js" />
function VFG() {}
VFG.Layer=function(){}
VFG.Controls=function(){}
VFG.Model=function(){}
VFG.Point=function(){}
;
///<jscompress sourcefile="VFGMouseEvent.js" />
VFG.MouseEvent=function(viewer, option){
	this.option = option;
	this.viewer = viewer;
	if(!this.viewer){
		console.log('参数必填！！！');
		return;
	}
	this.init();
}
/**
 * 初始化
 */
VFG.MouseEvent.prototype.init = function() {
	var _self = this;
	_self.handler = new Cesium.ScreenSpaceEventHandler(_self.viewer.scene.canvas);
    //左键点击操作
    _self.handler.setInputAction(function (movement) {
        var cartesian3 =VFG.Util.getScreenToC3(_self.viewer,movement.position);
        var entity = _self.viewer.scene.pick(movement.position);//选取当前的entity
        //拾取实体
        if (Cesium.defined(entity)){
	        if( _self.option.LEFT_CLICK_EN){
	        	 _self.option.LEFT_CLICK_EN(entity,movement.position);
	        }
        }
        //拾取屏幕坐标
        if (Cesium.defined(movement.position)){
	        if( _self.option.LEFT_CLICK_C2){
	        	 _self.option.LEFT_CLICK_C2(movement.position);
	        }
        }
        //拾取笛卡尔坐标
        if (Cesium.defined(cartesian3)){
	        if( _self.option.LEFT_CLICK_C3){
	        	 _self.option.LEFT_CLICK_C3(movement.position);
	        }
        }
        //拾取经纬度
        if (Cesium.defined(cartesian3)){
	        if( _self.option.LEFT_CLICK_LNLA){
	        	 _self.option.LEFT_CLICK_LNLA(VFG.Util.getC3ToLnLa(_self.viewer,cartesian3));
	        }
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    
    //鼠标移动事件
    _self.handler.setInputAction(function (movement) {
        var cartesian3 =VFG.Util.getScreenToC3(_self.viewer,movement.endPosition);
        var entity = _self.viewer.scene.pick(movement.endPosition);//选取当前的entity
        //拾取实体
        if (Cesium.defined(entity)){
	        if( _self.option.MOUSE_MOVE_EN){
	        	 _self.option.MOUSE_MOVE_EN(entity,movement.endPosition);
	        }
        }
        //拾取屏幕坐标
        if (Cesium.defined(movement.position)){
	        if( _self.option.MOUSE_MOVE_C2){
	        	 _self.option.MOUSE_MOVE_C2(movement.endPosition);
	        }
        }
        //拾取笛卡尔坐标
        if (Cesium.defined(cartesian3)){
	        if( _self.option.MOUSE_MOVE_C3){
	        	 _self.option.MOUSE_MOVE_C3(movement.posiendPositiontion);
	        }
        }
        //拾取经纬度
        if (Cesium.defined(cartesian3)){
	        if( _self.option.MOUSE_MOVE_LNLA){
	        	 _self.option.MOUSE_MOVE_LNLA(VFG.Util.getC3ToLnLa(_self.viewer,cartesian3));
	        }
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    //右键点击操作
    _self.handler.setInputAction(function (click) {
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};
/**
 * 销毁
 */
VFG.MouseEvent.prototype.destroy = function() {
	var _this=this;
    if( _this.option.end){
    	_this.option.end();
    };
    if( _this.handler){
    	_this.handler.destroy();
    	_this.handler = null;
    };
	delete _this.ops,
	delete _this.handler;
	return Cesium.destroyObject(_this);
};;
///<jscompress sourcefile="Globe.js" />
VFG.Globe=function(option){
	this.option = Cesium.defaultValue(option, Cesium.defaultValue.EMPTY_OBJECT);
	this.scene3DOnly=(option && option.scene3DOnly) ? option.scene3DOnly : true,
	this.selectionIndicator= (option && option.selectionIndicator) ? option.selectionIndicator :false,
	this.animation=(option && option.animation) ? option.animation : false,
	this.timeline= (option && option.timeline) ? option.timeline :false,
	this.navigationHelpButton=(option && option.navigationHelpButton) ? option.navigationHelpButton : false,
	this.fullscreenButton=(option && option.fullscreenButton) ? option.fullscreenButton : false,
	this.geocoder= (option && option.geocoder) ? option.geocoder :false,
	this.homeButton= (option && option.homeButton) ? option.homeButton :false,
	this.shouldAnimate= (option && option.shouldAnimate) ? option.shouldAnimate :false,
	this.sceneModePicker= (option && option.sceneModePicker) ? option.sceneModePicker :false,
	this.shouldAnimate= (option && option.shouldAnimate) ? option.shouldAnimate :true,
	this.infoBox= (option && option.infoBox) ? option.infoBox :false,
	this.requestRenderMode=(option && option.requestRenderMode) ? option.requestRenderMode : false,
	this.navigationInstructionsInitiallyVisible=(option && option.navigationInstructionsInitiallyVisible) ? option.navigationInstructionsInitiallyVisible :false,
	this.baseLayerPicker=(option && option.baseLayerPicker) ? option.baseLayerPicker :false,
	this.maximumRequests = (option && option.maximumRequests) ? option.maximumRequests :1024;
	this.maximumRequestsPerServer = (option && option.maximumRequestsPerServer) ? option.maximumRequestsPerServer :1024;
	this.throttleRequests = (option && option.throttleRequests) ? option.throttleRequests :true;
	this.defaultAccessToken = (option && option.defaultAccessToken) ? option.defaultAccessToken :'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJiZjliY2NhNS1iMThiLTQzZTYtOWM1ZS03NDMxMmY3YjIyNmUiLCJpZCI6MjAwNDcsInNjb3BlcyI6WyJhc2wiLCJhc3IiLCJhc3ciLCJnYyJdLCJpYXQiOjE1ODMxOTk3NTl9.lzdqsXU24bvovmmaRPXcD3jmSH0WmYTwmX6isCx8qfA';
	var _this = this;
	Cesium.RequestScheduler.maximumRequests = _this.maximumRequests;
	Cesium.RequestScheduler.maximumRequestsPerServer = _this.maximumRequestsPerServer;
	Cesium.RequestScheduler.throttleRequests = _this.throttleRequests;
	Cesium.Ion.defaultAccessToken = _this.defaultAccessToken;
	_this.viewer = new Cesium.Viewer(this.option.domId, {
		scene3DOnly: _this.scene3DOnly,
		selectionIndicator: _this.selectionIndicator,
		baseLayerPicker: _this.baseLayerPicker,
		animation: _this.animation,
		timeline: _this.timeline,
		navigationHelpButton: _this.navigationHelpButton,
		fullscreenButton: _this.fullscreenButton,
		geocoder: _this.geocoder,
		homeButton: _this.homeButton,
		shouldAnimate: _this.shouldAnimate,
		sceneModePicker: _this.sceneModePicker,
		shouldAnimate: _this.shouldAnimate,
		infoBox: _this.infoBox,
		requestRenderMode: _this.requestRenderMode,
		navigationInstructionsInitiallyVisible: _this.navigationInstructionsInitiallyVisible,
		baseLayerPicker: _this.baseLayerPicker,
		contextOptions: {
		webgl: {
			  alpha: true,
			  depth: true,
			  stencil: true,
			  antialias: true,
			  premultipliedAlpha: true,
			  preserveDrawingBuffer:true,
			  failIfMajorPerformanceCaveat:true
			}
		},
		imageryProvider: (_this.option && _this.option.imageryProvider) ?_this.option.imageryProvider: null
	});
	this.viewer.scene.globe.depthTestAgainstTerrain = false;
	this.viewer.cesiumWidget.creditContainer.style.display = "none";
	
    //设置操作习惯(禁止中间滑轮调整视角)
	this.viewer.scene.screenSpaceCameraController.zoomEventTypes = [Cesium.CameraEventType.WHEEL, Cesium.CameraEventType.PINCH];
	this.viewer.scene.screenSpaceCameraController.tiltEventTypes = [Cesium.CameraEventType.PINCH, Cesium.CameraEventType.RIGHT_DRAG];
	
	//解决模糊问题
	if(Cesium.FeatureDetection.supportsImageRenderingPixelated()){//判断是否支持图像渲染像素化处理
		this.viewer.resolutionScale = window.devicePixelRatio;
	}
	//是否开启抗锯齿
	this.viewer.scene.fxaa = true;
	this.viewer.scene.postProcessStages.fxaa.enabled = true;
	
	// 去掉entity的点击事件 start
	this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
	this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
	this.viewer.scene.globe.baseColor = new Cesium.Color.fromCssColorString("#546a53"); //地表背景色
	//限制缩放级别
	//this.viewer.scene.screenSpaceCameraController.maximumZoomDistance =9000000; //变焦时相机位置的最大值（以米为单位） 
	//this.viewer.scene.screenSpaceCameraController.minimumZoomDistance =1; //变焦时相机位置的最小量级（以米为单位）。默认为1.0。
	//this.viewer.scene.screenSpaceCameraController._zoomFactor = 3; //鼠标滚轮放大的步长参数 
	//this.viewer.scene.screenSpaceCameraController.minimumCollisionTerrainHeight = 15000000; //低于此高度时绕鼠标键绕圈，大于时绕视图中心点绕圈。
	
//	// 如果为真，则允许用户旋转相机。如果为假，相机将锁定到当前标题。此标志仅适用于2D和3D。
//    scene.screenSpaceCameraController.enableRotate = false;
//    // 如果为true，则允许用户平移地图。如果为假，相机将保持锁定在当前位置。此标志仅适用于2D和Columbus视图模式。
//    scene.screenSpaceCameraController.enableTranslate = false;
//    // 如果为真，允许用户放大和缩小。如果为假，相机将锁定到距离椭圆体的当前距离
//    scene.screenSpaceCameraController.enableZoom = false;
//    // 如果为真，则允许用户倾斜相机。如果为假，相机将锁定到当前标题。这个标志只适用于3D和哥伦布视图。
//    scene.screenSpaceCameraController.enableTilt = false;
	
	
	// 亮度设置
	var _this=this;
	this.viewer.dataSources.add(VFG.Polyline.Layers);
	this.viewer.scene.primitives.add(VFG.Polygon.Layers);//面
	this.viewer.scene.primitives.add(VFG.Model.Layers);//模型图层
	this.viewer.scene.primitives.add(VFG.Feature.Layers);//单体图层
	this.viewer.scene.primitives.add(VFG.Point.LabelCollection);
	this.viewer.scene.primitives.add(VFG.Point.PointPrimitiveCollection);
	this.viewer.scene.primitives.add(VFG.Point.BillboardCollection);
	this.viewer.scene.debugShowFramesPerSecond = false;
}
;
///<jscompress sourcefile="VFGCluster.js" />
VFG.Layer.Cluster=function(viewer,option){
	this.viewer=viewer;
	this.option=option;
	this.pixelRange = 15;
	this.minimumClusterSize = 3;
	this.enabled = true;
	this.Layers=option.Layers;
	this.init();
}

VFG.Layer.Cluster.prototype.init = function() {
	var _this = this;
	_this.viewer.dataSources.add(_this.Layers).then(function (dataSource) {
		  var pixelRange = 15;
		  var minimumClusterSize = 3;
		  var enabled = true;
		  dataSource.clustering.enabled = _this.enabled;
		  dataSource.clustering.pixelRange = _this.pixelRange;
		  dataSource.clustering.minimumClusterSize = _this.minimumClusterSize;

		  var removeListener;
		  function customStyle() {
		    if (Cesium.defined(removeListener)) {
		      removeListener();
		      removeListener = undefined;
		    } else {
		      removeListener = dataSource.clustering.clusterEvent.addEventListener(
		        function (clusteredEntities, cluster) {
		          cluster.label.show = false;
		          cluster.billboard.show = true;
		          cluster.billboard.id = cluster.label.id;
		          cluster.billboard.verticalOrigin =Cesium.VerticalOrigin.BOTTOM;

		            if (clusteredEntities.length >= 50) {
		                cluster.billboard.image = _this.getIconForRed(clusteredEntities.length,55,55);
		            } else if (clusteredEntities.length >= 40) {
		                cluster.billboard.image = _this.getIconForYellow(clusteredEntities.length,50,50);
		            } else if (clusteredEntities.length >= 30) {
		                cluster.billboard.image = _this.getIconForOrange(clusteredEntities.length,45,45);
		            } else if (clusteredEntities.length >= 20) {
		                cluster.billboard.image = _this.getIconForPurple(clusteredEntities.length,40,40);
		            } else if (clusteredEntities.length >= 10) {
		                cluster.billboard.image = _this.getIconForBlue(clusteredEntities.length,35,35);
		            } else {
		                cluster.billboard.image = _this.getIconForGreen(clusteredEntities.length,30,30);
		            }
		        }
		      );
		    }
		    var pixelRange = dataSource.clustering.pixelRange;
		    dataSource.clustering.pixelRange = 0;
		    dataSource.clustering.pixelRange = pixelRange;
		  }
		  customStyle();
    });
};

VFG.Layer.Cluster.prototype.getIconForRed=function(number,width,height) {
    var canvas=document.createElement('canvas');
    canvas.width=width||48;
    canvas.height=height||48;
    var ctx=canvas.getContext("2d");
    ctx.beginPath();
    ctx.fillStyle = 'rgba(255,0,0,0.5)'; // 红	
    ctx.arc(canvas.width/2,canvas.height/2,canvas.width/2,0,2*Math.PI, false);
    ctx.fill();
    ctx.beginPath();	
    ctx.fillStyle = 'rgba(255, 0,0,1)'; // 红	
    ctx.arc(canvas.width/2,canvas.height/2,canvas.width/2-5,0,2*Math.PI,false);
    ctx.fill();	
    ctx.fillStyle="rgb(255,255,255)";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.font="16px bold sans-serif";
    ctx.fillText(number,canvas.width/2,canvas.height/2+2);
    return  canvas.toDataURL("image/png")
}
VFG.Layer.Cluster.prototype.getIconForYellow=function(number,width,height) {
    var canvas=document.createElement('canvas');
    canvas.width=width||48;
    canvas.height=height||48;
    var ctx=canvas.getContext("2d");
    ctx.beginPath();
    ctx.fillStyle = 'rgba(255,255,0,0.5)'; // 红	
    ctx.arc(canvas.width/2,canvas.height/2,canvas.width/2,0,2*Math.PI, false);
    ctx.fill();
    ctx.beginPath();	
    ctx.fillStyle = 'rgba(255,255,0,1)'; // 红	
    ctx.arc(canvas.width/2,canvas.height/2,canvas.width/2-5,0,2*Math.PI,false);
    ctx.fill();	
    ctx.fillStyle="rgb(255,255,255)";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.font="16px bold sans-serif";
    ctx.fillText(number,canvas.width/2,canvas.height/2+2);
    return  canvas.toDataURL("image/png")
}
VFG.Layer.Cluster.prototype.getIconForOrange=function(number,width,height) {
    var canvas=document.createElement('canvas');
    canvas.width=width||48;
    canvas.height=height||48;
    var ctx=canvas.getContext("2d");
    ctx.beginPath();
    ctx.fillStyle = 'rgba(255,165,0,0.5)'; // 红	
    ctx.arc(canvas.width/2,canvas.height/2,canvas.width/2,0,2*Math.PI, false);
    ctx.fill();
    ctx.beginPath();	
    ctx.fillStyle = 'rgba(255,165,0,1)'; // 红	
    ctx.arc(canvas.width/2,canvas.height/2,canvas.width/2-5,0,2*Math.PI,false);
    ctx.fill();	
    ctx.fillStyle="rgb(255,255,255)";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.font="16px bold sans-serif";
    ctx.fillText(number,canvas.width/2,canvas.height/2+2);
    return  canvas.toDataURL("image/png")
}

VFG.Layer.Cluster.prototype.getIconForPurple=function(number,width,height) {
    var canvas=document.createElement('canvas');
    canvas.width=width||48;
    canvas.height=height||48;
    var ctx=canvas.getContext("2d");
    ctx.beginPath();
    ctx.fillStyle = 'rgba(160,32,240,0.5)'; // 红	
    ctx.arc(canvas.width/2,canvas.height/2,canvas.width/2,0,2*Math.PI, false);
    ctx.fill();
    ctx.beginPath();	
    ctx.fillStyle = 'rgba(160,32,240,1)'; // 红	
    ctx.arc(canvas.width/2,canvas.height/2,canvas.width/2-5,0,2*Math.PI,false);
    ctx.fill();	
    ctx.fillStyle="rgb(255,255,255)";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.font="16px bold sans-serif";
    ctx.fillText(number,canvas.width/2,canvas.height/2+2);
    return  canvas.toDataURL("image/png")
}
VFG.Layer.Cluster.prototype.getIconForBlue=function(number,width,height) {
    var canvas=document.createElement('canvas');
    canvas.width=width||48;
    canvas.height=height||48;
    var ctx=canvas.getContext("2d");
    ctx.beginPath();
    ctx.fillStyle = 'rgba(0,0,255,0.5)'; // 红	
    ctx.arc(canvas.width/2,canvas.height/2,canvas.width/2,0,2*Math.PI, false);
    ctx.fill();
    ctx.beginPath();	
    ctx.fillStyle = 'rgba(0,0,255,1)'; // 红	
    ctx.arc(canvas.width/2,canvas.height/2,canvas.width/2-5,0,2*Math.PI,false);
    ctx.fill();	
    ctx.fillStyle="rgb(255,255,255)";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.font="16px bold sans-serif";
    ctx.fillText(number,canvas.width/2,canvas.height/2+2);
    return  canvas.toDataURL("image/png")
}

VFG.Layer.Cluster.prototype.getIconForGreen=function(number,width,height) {
    var canvas=document.createElement('canvas');
    canvas.width=width||48;
    canvas.height=height||48;
    var ctx=canvas.getContext("2d");
    ctx.beginPath();
    ctx.fillStyle = 'rgba(0,255,0,0.5)'; // 红	
    ctx.arc(canvas.width/2,canvas.height/2,canvas.width/2,0,2*Math.PI, false);
    ctx.fill();
    ctx.beginPath();	
    ctx.fillStyle = 'rgba(0,255,0,1)'; // 红	
    ctx.arc(canvas.width/2,canvas.height/2,canvas.width/2-5,0,2*Math.PI,false);
    ctx.fill();	
    ctx.fillStyle="rgb(255,255,255)";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.font="16px bold sans-serif";
    ctx.fillText(number,canvas.width/2,canvas.height/2+2);
    return  canvas.toDataURL("image/png")
}
VFG.Layer.Cluster.prototype.remove=function(){
	var values=this.Layers.entities.values;
	for(var i=0;i<values.length;i++){
		if(values[i].id){
			VFG.Point.Primitives.delete(values[i].id)
		}
	}
}
/**/

VFG.Layer.Cluster.prototype.destroy = function() {
	
	if(this.Layers){
		this.remove();
		this.viewer.dataSources.remove(this.Layers);
	}
    delete this.option,
    delete this.viewer
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="VFGListener.js" />
/**
 * viewer
 * option{
 * 	position:{
 * 		x:经度
 * 		y:维度
 * 		z:高度
 * 	},
 *  callBack:fun(e)回调函数
 * }
 * 
 */
VFG.Listener=function(viewer,option){
	this.option = Cesium.defaultValue(option, Cesium.defaultValue.EMPTY_OBJECT);
	if (!option) {
		console.log('参数必填!');
		return;
	}
	if (!viewer) {
		console.log('参数必填!');
		return;
	}
	this.option = option;
	this.viewer = viewer;
	this.id=option.id;
	
	this.position;
	if(VFG.Point.getById(this.id)){
		this.position =VFG.Point.getById(this.id).position.getValue();
	}else{
		this.position = Cesium.Cartesian3.fromDegrees(option.position.x*1, option.position.y*1, option.position.z*1);
	}
	
//	this.position = option.position;
	this.callBack = option.callBack;
	if(!this.position){
		console.log('参数必填!');
		return;
	}
	this.init();
}

/**
 * 初始化
 */
VFG.Listener.prototype.init=function(){
	var _this=this;
	if(_this.position){
		_this.event=function(){
			var cartesian2=Cesium.SceneTransforms.wgs84ToWindowCoordinates(_this.viewer.scene, _this.position);
			if (Cesium.defined(cartesian2)){
				if(_this.callBack){
					_this.callBack(cartesian2);
				}
			}
		}
		_this.viewer.scene.postRender.addEventListener(_this.event);
	}else{
		console.log('初始化失败，检测是否有效经纬度!!!');
	}
}

VFG.Listener.prototype.update=function(position){
	var _this=this;
	if(position){
		_this.position= Cesium.Cartesian3.fromDegrees(option.position.x*1, option.position.y*1, option.position.z*1);
	}
}

/**
 * 销毁
 */
VFG.Listener.prototype.destroy=function(){
	var _this = this;
	if(_this.event){
		_this.viewer.scene.postRender.removeEventListener(_this.event);
	}
	delete this.option,
	delete this.callBack,
	delete this.viewer,
	delete this.position;
	return Cesium.destroyObject(this);
}
;
///<jscompress sourcefile="VFGFeature.js" />
VFG.Feature=function(){
}
VFG.Feature.Layers= new Cesium.PrimitiveCollection();
VFG.Feature.Map= new Map();

/**
 * id查询点
 */
VFG.Feature.getById=function(id){
	if(this.Map.has(id)){
		return this.Map.get(id);
	}
}

/**
 * 删除单体
 */
VFG.Feature.removeById=function(id){
	if(this.Map.has(id)){
		var classification =this.Map.get(id);
		if(this.Layers.remove(classification.primitive)){
			classification=null;
			this.Map.delete(id);
			return true;
		}
	}
}

VFG.Feature.add=function(params){
	var classification =new VFG.ClassificationPrimitive(params);
	if(classification && classification.primitive){
		this.Layers.add(classification.primitive);
		this.Map.set(classification.id,classification);
	}
	return classification;
}

/**
 * 平移
 */
VFG.Feature.translate=function(id,position){
	var modelFeature=this.getById(id);
	if(!modelFeature){
		return;
	}
    modelFeature.translateFeature(position);
}

/**
 * 更新尺寸
 */
VFG.Feature.setDimensions=function(id,dimensions){
	var modelFeature=this.getById(id);
	if(!modelFeature){
		return;
	}
	this.Layers.remove(modelFeature.primitive)
	modelFeature.setDimensions(dimensions);
	if(modelFeature && modelFeature.primitive){
		this.Layers.add(modelFeature.primitive);
	}
}

/**
 * 设置颜色
 */
VFG.Feature.setNormalColor=function(id,color){
	var modelFeature=this.getById(id);
	if(!modelFeature){
		return;
	}
    modelFeature.setNormalColor(color) ;
}

/**
 * 设置悬浮颜色
 */
VFG.Feature.setHoverColor=function(id,color){
	var modelFeature=this.getById(id);
	if(!modelFeature){
		return;
	}
    modelFeature.setHoverColor(color) ;
}

/**
 * 是否长显示
 */
VFG.Feature.setDisplay=function(id,isView){
	var modelFeature=this.getById(id);
	if(!modelFeature){
		return;
	}
    modelFeature.setDisplay(isView);
}

/**
 * 旋转
 */
VFG.Feature.rotate=function(id,rotation){
	var modelFeature=this.getById(id);
	if(!modelFeature){
		return;
	}
	modelFeature.rotateFeature(rotation);
}


VFG.Feature.show=function(viewer,option){
	
}

VFG.Feature.update=function(option){
	var modelFeature=this.getById(option.id);
	if(!modelFeature){
		return;
	}
	
	if(option.isView){
		this.setDisplay(option.id,option.isView);
	}
	
	if(option.position){
		this.translate(option.id,option.position);
	}
	
	if(option.dimensions){
		this.setDimensions(option.id,option.dimensions);
	}
	
	if(option.rotation){
		this.rotate(option.id,option.rotation);
	}
	
	if(option.normalColor){
		this.setNormalColor(option.id,option.normalColor);
	}
	if(option.hoverColor){
		this.setHoverColor(option.id,option.hoverColor);
	}
	
}

;
///<jscompress sourcefile="VFGModel.js" />
VFG.Model=function(){
}
VFG.Model.Layers= new Cesium.PrimitiveCollection();
VFG.Model.Primitives=new Map();

VFG.Model.addModel=function(viewer,ops,localModelUrl,isLocal){
	if('GLTF'==ops.type){
		this.createGltfPrimitive(viewer,ops,localModelUrl,isLocal);
	}
	else if('3DTILES'==ops.type){
		this.create3DTilePrimitive(viewer,ops,localModelUrl,isLocal);
	}
}

VFG.Model.createGltfPrimitive=function(viewer,ops,localModelUrl,isLocal){
	var _this=this;
	if(!ops){
		console.log('参数必填!!!');
		return;
	}
	
	if(!ops.url){
		console.log('模型地址必填!!!');
		return;
	}
	
	if('GLTF'!=ops.type){
		console.log('模型格式必需是GLTF!!!');
		return;
	}
	if(!(ops.x && ops.y)){
		console.log('坐标必填!!!');
		return;
	}
/*	viewer.scene.light = new Cesium.DirectionalLight({ //去除时间原因影响模型颜色
         direction: new Cesium.Cartesian3(0.35492591601301104, -0.8909182691839401, -0.2833588392420772)
       })*/
	if(!this.Primitives.has(ops.id)){
		var distanceDisplayCondition =VFG.Util.getDistanceDisplayCondition(ops.displayNear,ops.displayFar);
		var model = this.Layers.add(Cesium.Model.fromGltf({
			id:ops.id,
			name:ops.name||'未命名',
			url: ops.url,
			type:ops.type,
			bizType:ops.code||'',
			show : ( ops.show &&  ops.show!='1')?false : true,                     
			modelMatrix : this.getModelMatrix(ops),
			scale: ops.scale*1||1,
			minimumPixelSize:(ops.minimumPixelSize)?ops.minimumPixelSize*1:0,
			maximumScale:(ops.minimumPixelSize)?ops.minimumPixelSize*1:undefined,
			allowPicking : true,        
			debugShowBoundingVolume : false, 
			debugWireframe : false,
			distanceDisplayCondition:distanceDisplayCondition?distanceDisplayCondition:undefined,
			backFaceCulling:false,
			//colorBlendMode:(ops.oftenShow=="1")?this.getColorBlendMode(ops.colorBlendMode):null,  //设置颜色与原纹理的混合关系
			//silhouetteColor:(ops.oftenShow=="1")? (ops.silhouetteColor? Cesium.Color.fromCssColorString(ops.silhouetteColor):Cesium.Color.BLACK):null,		
			//silhouetteSize:(ops.oftenShow=="1")? ops.silhouetteSize*1:null,		
			//color:(ops.oftenShow=="1")?  (ops.color? Cesium.Color.fromCssColorString(ops.color):Cesium.Color.fromCssColorString("rgba(255,255,255,1)")):Cesium.Color.fromCssColorString("rgba(255,255,255,1)"),			
		}));
		
		
		
		
		model.readyPromise.then(function(model) {
	       model.activeAnimations.addAll({
	         loop:_this.getLoop(ops.loop),//控制重复
	         speedup:ops.loop?ops.loop*1: 0.5, // 速度，相对于clock
	         reverse: ops.reverse?ops.reverse*1:false // 动画反转
	       })
		}).otherwise(function(error){
	    });
		this.Primitives.set(ops.id,model);
		return model;
	}else{
		return this.Primitives.get(ops.id);
	}
}

VFG.Model.create3DTilePrimitive=function(viewer,ops,localModelUrl,isLocal){
	var _this=this;
	if(!ops){
		console.log('参数必填!!!');
		return;
	}
	
	if(!ops.url){
		console.log('模型地址必填!!!');
		return;
	}
	
	if('3DTILES'!=ops.type){
		console.log('模型格式必需是3DTILES!!!');
		return;
	}
	
	if(!this.Primitives.has(ops.id)){
		var url=ops.url;
		if(isLocal==true){
			var protocol = window.location.protocol;
			if('https:'==protocol){
				url=url.replace(localModelUrl, "https://localhost:888")
			}else{
				url=url.replace(localModelUrl, "http://localhost")
			}
		}
		var primitive=this.Layers.add(new Cesium.Cesium3DTileset({
			id : ops.id,
			url : url,
			name : ops.name ||'未命名',
			show : ( ops.show &&  ops.show!='1')?false : true,    
			bizType:ops.code||'',
			preferLeaves:(ops && ops.preferLeaves && ops.preferLeaves=='1')?true:false,
			imageBasedLightingFactor :Cesium.Cartesian2(1.0, 1.0),
			loadSiblings:true,
			skipLevels:ops.skipLevels ? ops.skipLevels*1: 1,
			baseScreenSpaceError:ops.baseScreenSpaceError ? ops.baseScreenSpaceError*1: 1024,
			skipScreenSpaceErrorFactor:ops.skipScreenSpaceErrorFactor ? ops.skipScreenSpaceErrorFactor*1: 16,
			maximumMemoryUsage:ops.maximumMemoryUsage ? ops.maximumMemoryUsage*1: 512,
			maximumScreenSpaceError : ops.maximumScreenSpaceError ? ops.maximumScreenSpaceError*1: 16,
			skipLevelOfDetail : ops.skipLevelOfDetail ? (ops.skipLevelOfDetail=='on'?true:false): false,
			maximumNumberOfLoadedTiles : ops.maximumNumberOfLoadedTiles ? ops.maximumNumberOfLoadedTiles*1: 1024, //最大加载瓦片个数			
		}));
		
		primitive.readyPromise.then(function(tileset) {
			if(ops.x && ops.y ){
	                tileset._root.transform=_this.get3dtilesMaxtrix(ops);
	               // tileset._root.transform =_this.get3dtilesMaxtrix(ops);
			}else{
	            var heightOffset =ops.z || 0;  //高度
	            var boundingSphere = tileset.boundingSphere; 
	            var cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);
	            var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
	            var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset);
	            var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
	            tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
			}
			
		    if(ops.callBack){
		    	var param=VFG.Util.getCenterForModel(tileset,tileset._root.transform);
		    	ops.callBack({
		    		state:true,
		    		message:'成功',
		    		param:param
		    	});
		    }
		    
		}).otherwise(function(error){
		    if(ops.callBack){
		    	ops.callBack({
		    		state:false,
		    		message:error
		    	});
		    }
	    });
		
		primitive.allTilesLoaded.addEventListener(function() {
            console.log('All tiles are loaded');
        });
		
		this.Primitives.set(ops.id,primitive);
		return primitive;
	}else{
		return this.Primitives.get(ops.id);
	}
}

/**
 * id查询点
 */
VFG.Model.getById=function(id){
	if(this.Primitives.has(id)){
		return this.Primitives.get(id);
	}
}


/**
 * 显示隐藏
 */
VFG.Model.showOrHideById=function(id,state){
	if(this.Primitives.has(id)){
		this.Primitives.get(id).show=state;
	}
}

VFG.Model.show=function(option){
	if(this.Primitives.has(option.id)){
		this.Primitives.get(option.id).show=option.show;
	}
} 

VFG.Model.removeById=function(id){ 
	if(this.Primitives.has(id)){
		if(this.Layers.remove(this.Primitives.get(id))){
			this.Primitives.delete(id);
		}
	}
}

VFG.Model.getModelMatrix=function(ops){
	var heading = Cesium.defaultValue(ops.ry, 0.0);
    var pitch = Cesium.defaultValue(ops.rx, 0.0);
    var roll = Cesium.defaultValue(ops.rz, 0.0);
    var headingPitchRoll = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(heading), Cesium.Math.toRadians(pitch), Cesium.Math.toRadians(roll));
    var origin = Cesium.Cartesian3.fromDegrees(ops.x*1, ops.y*1,ops.z*1);
	return Cesium.Transforms.headingPitchRollToFixedFrame(origin, headingPitchRoll, Cesium.Ellipsoid.WGS84, Cesium.Transforms.eastNorthUpToFixedFrame, new Cesium.Matrix4());
}
VFG.Model.get3dtilesMaxtrix=function(ops){
	 var rx = Cesium.defaultValue(ops.rx, 0.0);
    var ry = Cesium.defaultValue(ops.ry, 0.0);
    var rz = Cesium.defaultValue(ops.rz, 0.0);
    var transformPosition =Cesium.Cartesian3.fromDegrees(ops.x*1, ops.y*1,ops.z*1);
    var matrix = Cesium.Transforms.eastNorthUpToFixedFrame(transformPosition);
    var scale = Cesium.Matrix4.fromUniformScale(ops.scale*1);
    Cesium.Matrix4.multiply(matrix, scale, matrix);
    
    var rotationX = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(rx));
    var rotationY = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(ry));
    var rotationZ = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(rz));
    
    
    var rotationTranslationX = Cesium.Matrix4.fromRotationTranslation(rotationX);
    var rotationTranslationY = Cesium.Matrix4.fromRotationTranslation(rotationY);
    var rotationTranslationZ = Cesium.Matrix4.fromRotationTranslation(rotationZ);
    
    Cesium.Matrix4.multiply(matrix, rotationTranslationX, matrix);
    Cesium.Matrix4.multiply(matrix, rotationTranslationY, matrix);
    Cesium.Matrix4.multiply(matrix, rotationTranslationZ, matrix);
    return matrix;
}



VFG.Model.update = function(ops) {
	var _this = this;
	if(this.Primitives.has(ops.id)){
		this.Primitives.get(ops.id).modelMatrix=_this.getModelMatrix(ops);
	}
};

VFG.Model.updateScale = function(ops) {
	var _this = this;
	if(this.Primitives.has(ops.id)){
		this.Primitives.get(ops.id).scale=ops.scale*1;
	}
};

VFG.Model.getColorBlendMode = function(value) {
	var _this = this;
	if("0"==value){
		return Cesium.ColorBlendMode.HIGHLIGHT;//材质与设置颜色相乘得到的颜色。
	}
	else if("1"==value){
		return Cesium.ColorBlendMode.MIX;//材质与设置颜色混合得到的颜色，是怎么混合的，还需要研究源码。
	}
	else if("2"==value){
		return Cesium.ColorBlendMode.REPLACE;//设置颜色替换材质。
	}
};

VFG.Model.getLoop = function(value) {
	var _this = this;
	if("0"==value){
		return Cesium.ModelAnimationLoop.MIRRORED_REPEAT;
	}
	else if("1"==value){
		return Cesium.ModelAnimationLoop.NONE;
	}
	else if("2"==value){
		return Cesium.ModelAnimationLoop.REPEAT;
	}else{
		return Cesium.ModelAnimationLoop.MIRRORED_REPEAT;
	}
};

VFG.Model.updateHighlight = function(ops) {
	var _this = this;
	if(this.Primitives.has(ops.id)){
		var Primitive=this.Primitives.get(ops.id);
		if(ops.oftenShow=="1"){
			if(ops.color) Primitive.color =Cesium.Color.fromCssColorString(ops.color)
			if(ops.colorBlendMode) Primitive.colorBlendMode=this.getColorBlendMode(ops.colorBlendMode);
			if(ops.silhouetteColor) Primitive.silhouetteColor= Cesium.Color.fromCssColorString(ops.silhouetteColor);
			if(ops.silhouetteSize) Primitive.silhouetteSize=ops.silhouetteSize*1;
		}else{
			Primitive.color =Cesium.Color.fromCssColorString("rgba(255,255,255,1)");//设置模型颜色与透明度
			Primitive.colorBlendMode=Cesium.ColorBlendMode.HIGHLIGHT;
			Primitive.silhouetteColor=null;
			Primitive.silhouetteSize=null;
		}
	}
};

VFG.Model.select = function(ops) {
	var _this = this;
	if(this.Primitives.has(ops.id)){
		var Primitive=this.Primitives.get(ops.id);
		if(ops.oftenShow=="1"){
			if(ops.color) Primitive.color =Cesium.Color.fromCssColorString(ops.color)
			if(ops.colorBlendMode) Primitive.colorBlendMode=this.getColorBlendMode(ops.colorBlendMode);
			if(ops.silhouetteColor) Primitive.silhouetteColor= Cesium.Color.fromCssColorString(ops.silhouetteColor);
			if(ops.silhouetteSize) Primitive.silhouetteSize=ops.silhouetteSize*1;
		}
	}
};

VFG.Model.unselect = function(ops) {
	var _this = this;
	if(this.Primitives.has(ops.id)){
		var Primitive=this.Primitives.get(ops.id);
		if(ops.oftenShow=="1"){
			Primitive.color =Cesium.Color.fromCssColorString("rgba(255,255,255,1)");//设置模型颜色与透明度
			Primitive.colorBlendMode=Cesium.ColorBlendMode.HIGHLIGHT;
			Primitive.silhouetteColor=null;
			Primitive.silhouetteSize=null;
		}
	}
};





;
///<jscompress sourcefile="VFGPoint.js" />
VFG.Point=function(){}

VFG.Point.LabelCollection=new Cesium.LabelCollection();
VFG.Point.PointPrimitiveCollection=new Cesium.PointPrimitiveCollection();
VFG.Point.BillboardCollection=new Cesium.BillboardCollection();

VFG.Point.Primitives=new Map();
VFG.Point.LabelMap=new Map();
VFG.Point.PointMap=new Map();
VFG.Point.BillboardMap=new Map();

VFG.Point.add=function(viewer,item,ctx){
	if(!this.contain(item.id)){
		if(item.render && item.render=="1"){
			this.addEntity(viewer,item,ctx);
		}else{
			this.addOrUpdatePrimitive(viewer,item,ctx);
		}
		this.Primitives.set(item.point.id,{
			id:item.point.id,
			render:item.point.render||"0"
		})
	}
}

VFG.Point.addOrUpdatePrimitive=function(viewer,item,ctx){
	var param=this.packagePrimitive(viewer,item,ctx);
	var point=item.point;
	if(param.label){
		if(this.LabelMap.has(point.id)){
			var label=this.LabelMap.get(point.id);
			label.text=param.label.text|| '点';
			label.position=param.label.position,
			label.font=param.label.font;
			label.horizontalOrigin =param.label.horizontalOrigin;
			label.verticalOrigin =param.label.verticalOrigin;
			label.scale=param.label.scale;
			label.fillColor =param.label.fillColor;
			label.outlineWidth =param.label.outlineWidth;
			label.outlineColor=param.label.outlineColor;
			label.pixelOffset=param.label.pixelOffset;
			label.showBackground=param.label.showBackground;
			label.backgroundColor=param.label.backgroundColor
			label.backgroundPadding =param.label.backgroundPadding
			label.pixelOffsetScaleByDistance =param.label.pixelOffsetScaleByDistance
			label.scaleByDistance=param.label.scaleByDistance
			label.translucencyByDistance=param.label.translucencyByDistance       		
			label.distanceDisplayCondition =param.label.distanceDisplayCondition
			label.style =label.style
		}else{
	        this.LabelMap.set(point.id,this.LabelCollection.add(param.label));
		}
	}else{
		if(this.LabelMap.has(point.id)){
			this.LabelCollection.remove(this.LabelMap.get(point.id));
			this.LabelMap.delete(point.id);
		}
	}
	if(param.billboard){
		if(this.BillboardMap.has(point.id)){
			var billboard=this.BillboardMap.get(point.id);
			billboard.position=param.billboard.position;
			billboard.image=param.billboard.image;
			billboard.width=param.billboard.width
			billboard.height=param.billboard.height
			billboard.scale=param.billboard.scale
			billboard.sizeInMeters=param.billboard.sizeInMeters
			billboard.pixelOffset=param.billboard.pixelOffset
			billboard.eyeOffset=param.billboard.eyeOffset
			billboard.horizontalOrigin =param.billboard.horizontalOrigin
			billboard.verticalOrigin =param.billboard.verticalOrigin 
			billboard.pixelOffsetScaleByDistance =param.billboard.pixelOffsetScaleByDistance
			billboard.distanceDisplayCondition =param.billboard.distanceDisplayCondition
			billboard.scaleByDistance=param.billboard.scaleByDistance
			billboard.translucencyByDistance=param.billboard.translucencyByDistance
		}else{
	        this.BillboardMap.set(point.id,this.BillboardCollection.add(param.billboard));
		}
	}else{
		if(this.BillboardMap.has(point.id)){
			this.BillboardCollection.remove(this.BillboardMap.get(point.id));
			this.BillboardMap.delete(point.id)
		}
	}
	if(param.point){
		if(this.PointMap.has(point.id)){
			var point=this.PointMap.get(point.id);
			point.position=param.point.position
			point.pixelSize =param.point.pixelSize
			//heightReference=param.point.heightReference?point.heightReference: Cesium.HeightReference.NONE,
			point.color =param.point.color
			point.outlineColor=param.point.outlineColor
			point.outlineWidth=param.point.outlineWidth
			point.distanceDisplayCondition =param.point.distanceDisplayCondition
			point.scaleByDistance=param.point.scaleByDistance
			point.translucencyByDistance=param.point.translucencyByDistance
	        //disableDepthTestDistance: Number.POSITIVE_INFINITY
		}else{
	        this.PointMap.set(point.id,this.PointPrimitiveCollection.add(param.point));
		}
	}else{
		if(this.PointMap.has(point.id)){
			this.PointPrimitiveCollection.remove(this.PointMap.get(point.id));
			this.PointMap.delete(point.id);
		}
	}
}

VFG.Point.packagePrimitive=function(viewer,item,ctx){
	 var point=item.point;
	 var style=item.style;
	 var position=Cesium.Cartesian3.fromDegrees(point.x*1,point.y*1,point.z*1);
	 var param={};
	 if(style){
		 if(style.showForLabel=='1'){
			var eyeOffset=VFG.Util.getCartesian3(style.eyeOffsetXForLabel,style.eyeOffsetYForLabel,style.eyeOffsetZForLabel);
			var pixelOffset=VFG.Util.getCartesian2(style.pixelOffsetXForLabel*1,style.pixelOffsetYForLabel);
			var backgroundPadding=VFG.Util.getCartesian2(style.backgroundPaddingXForLabel,style.backgroundPaddingYForLabel);
			var pixelOffsetScaleByDistance= VFG.Util.getNearFarScalar(style.pixelOffsetScaleNearForLabel,style.pixelOffsetScaleNearValueForLabel, style.pixelOffsetScaleFarForLabel,style.pixelOffsetScaleFarValueForLabel);
		    var scaleByDistance=VFG.Util.getNearFarScalar(style.scalarNearForLabel,style.scalarNearValueForLabel, style.scalarFarForLabel,style.scalarFarValueForLabel); 
		    var translucencyByDistance =VFG.Util.getNearFarScalar(style.translucencyNearForLabel,style.translucencyNearValueForLabel, style.translucencyFarForLabel,style.translucencyFarValueForLabel); 
		    var distanceDisplayCondition =VFG.Util.getDistanceDisplayCondition(style.displayNearForLabel,style.displayFarForLabel);
		    param.label={
		    	id: point.id,
		    	text:point.name|| '点',
		    	position:position,
		        font: this.getFont(style),
		        //eyeOffset :eyeOffset?eyeOffset:Cesium.Cartesian3.ZERO ,
		        horizontalOrigin : VFG.Util.getHorizontalOrigin(style.horizontalOriginForLabel) ,
		        verticalOrigin : VFG.Util.getVerticalOrigin(style.verticalOriginForLabel) ,
		        scale: style.fontScaleForLabel?style.fontScaleForLabel:1,
		        fillColor :style.fillColorForLabel?Cesium.Color.fromCssColorString(style.fillColorForLabel):Cesium.Color.WHITE,
		        outlineWidth : style.outlineWidthForLabel?style.outlineWidthForLabel:0,
		        outlineColor:  style.outlineColorForLabel?Cesium.Color.fromCssColorString(style.outlineColorForLabel):Cesium.Color.WHITE,
		        pixelOffset: pixelOffset?pixelOffset:new Cesium.Cartesian2(0, 0),
		        showBackground: style.showBackgroundForLabel&& style.showBackgroundForLabel==1 ? true:false,
		        backgroundColor: style.backgroundColorForLabel?Cesium.Color.fromCssColorString(style.backgroundColorForLabel):new Cesium.Color(0.165, 0.165, 0.165, 0.8),
		        backgroundPadding : backgroundPadding?backgroundPadding:new Cesium.Cartesian2(0, 0),
		        pixelOffsetScaleByDistance :pixelOffsetScaleByDistance?pixelOffsetScaleByDistance:undefined,//偏移量比例
		        scaleByDistance:scaleByDistance?scaleByDistance:undefined, //缩放比例
		        translucencyByDistance:translucencyByDistance?translucencyByDistance:undefined,//半透明度比例            		
		        distanceDisplayCondition :distanceDisplayCondition?distanceDisplayCondition:undefined,
		        style :Cesium.LabelStyle.FILL_AND_OUTLINE,
		        disableDepthTestDistance: Number.POSITIVE_INFINITY
		    };
		 }
		 if(style.showForBillboard=='1'){
			var pixelOffset=VFG.Util.getCartesian2(style.pixelOffsetXForBillboard*1,style.pixelOffsetXForBillboard*1);
			var pixelOffsetScaleByDistance= VFG.Util.getNearFarScalar(style.pixelOffsetScaleNearForBillboard,style.pixelOffsetScaleNearValueForBillboard, style.pixelOffsetScaleFarForBillboard,style.pixelOffsetScaleFarValueForBillboard);
	        var distanceDisplayCondition =VFG.Util.getDistanceDisplayCondition(style.displayNearForBillboard,style.displayFarForBillboard);
	        var scaleByDistance= VFG.Util.getNearFarScalar(style.scalarNearForBillboard,style.scalarNearValueForBillboard, style.scalarFarForBillboard,style.scalarFarValueForBillboard); 
	        var translucencyByDistance =VFG.Util.getNearFarScalar(style.translucencyNearForBillboard,style.translucencyNearValueForBillboard, style.translucencyFarForBillboard,style.translucencyFarValueForBillboard); 
	        param.billboard={
	        	id: point.id,
	        	position: position,
	            image:ctx+style.imageForBillboard,
	            width: style.widthForBillboard,
	            height: style.heightForBillboard,
	            scale:style.scaleForBillboard,
	            sizeInMeters: false,
		        pixelOffset: pixelOffset?pixelOffset:new Cesium.Cartesian2(0, style.heightForBillboard),
	            eyeOffset:new Cesium.Cartesian3(0.0, 0, 0.0),
	            horizontalOrigin : Cesium.HorizontalOrigin.CENTER,
	            verticalOrigin :Cesium.VerticalOrigin.BOTTOM,
		        pixelOffsetScaleByDistance :pixelOffsetScaleByDistance?pixelOffsetScaleByDistance:undefined,//偏移量比例
	            distanceDisplayCondition :distanceDisplayCondition?distanceDisplayCondition:undefined,
	            scaleByDistance:scaleByDistance?scaleByDistance:undefined, //设置距离方位内
	            translucencyByDistance:translucencyByDistance?translucencyByDistance:undefined,
	            disableDepthTestDistance: Number.POSITIVE_INFINITY		
	    	}
		 }
		 if(style.showForPoint=='1'){
		    var distanceDisplayCondition =VFG.Util.getDistanceDisplayCondition(style.displayNearForPoint,style.displayFarForPoint);
		    var scaleByDistance= VFG.Util.getNearFarScalar(style.scalarNearForPoint,style.scalarNearValueForPoint, style.scalarFarForPoint,style.scalarFarValueForPoint); 
		    var translucencyByDistance= VFG.Util.getNearFarScalar(style.translucencyNearForPoint,style.translucencyNearValueForPoint, style.translucencyFarForPoint,style.translucencyFarValueForPoint); 
		    param.point={
		    	id: point.id,
		    	position: position,
				pixelSize : style.pixelSizeForPoint||5,
				//heightReference:point.heightReference?point.heightReference: Cesium.HeightReference.NONE,
				color :style.colorForPoint?Cesium.Color.fromCssColorString(style.colorForPoint):Cesium.Color.WHITE,
				outlineColor: style.outlineColorForPoint? Cesium.Color.fromCssColorString(style.outlineColorForPoint):Cesium.Color.BLACK,
			    outlineWidth:style.outlineWidthForPoint?style.outlineWidthForPoint:0,
		        distanceDisplayCondition : distanceDisplayCondition?distanceDisplayCondition:undefined,
		        scaleByDistance:scaleByDistance?scaleByDistance:undefined, 
		        translucencyByDistance:translucencyByDistance?translucencyByDistance:undefined, 	
		        disableDepthTestDistance: Number.POSITIVE_INFINITY
			}
		 }
		 return param;
	 }else{
	    param.point={
			  id: point.id,
	          pixelSize: 5,
	          color: Cesium.Color.RED,
	          color :new Cesium.Color ( 255 , 255 , 0 , 1 ),
	          outlineColor : Cesium.Color.YELLOW,
	          outlineWidth :2,
	          position: position
		}
	    return param;
	 }
}


VFG.Point.addEntity=function(viewer,item,ctx){
	return new Cesium.Entity(this.packageEntity(viewer,item,ctx));
}

VFG.Point.packageEntity=function(viewer,item,ctx){
	 var point=item.point;
	 var ops=item.style;
	 var position=Cesium.Cartesian3.fromDegrees(point.x*1,point.y*1,point.z*1);
	 if(ops){
			var param={
				  id: point.id,
		          position: position,
		          code: point.code,
			};
			if(ops.showForLabel=='1'){
				var eyeOffset=VFG.Util.getCartesian3(ops.eyeOffsetXForLabel,ops.eyeOffsetYForLabel,ops.eyeOffsetZForLabel);
				var pixelOffset=VFG.Util.getCartesian2(ops.pixelOffsetXForLabel*1,ops.pixelOffsetYForLabel);
				var backgroundPadding=VFG.Util.getCartesian2(ops.backgroundPaddingXForLabel,ops.backgroundPaddingYForLabel);
				var pixelOffsetScaleByDistance= VFG.Util.getNearFarScalar(ops.pixelOffsetScaleNearForLabel,ops.pixelOffsetScaleNearValueForLabel, ops.pixelOffsetScaleFarForLabel,ops.pixelOffsetScaleFarValueForLabel);
			    var scaleByDistance=VFG.Util.getNearFarScalar(ops.scalarNearForLabel,ops.scalarNearValueForLabel, ops.scalarFarForLabel,ops.scalarFarValueForLabel); 
			    var translucencyByDistance =VFG.Util.getNearFarScalar(ops.translucencyNearForLabel,ops.translucencyNearValueForLabel, ops.translucencyFarForLabel,ops.translucencyFarValueForLabel); 
			    var distanceDisplayCondition =VFG.Util.getDistanceDisplayCondition(ops.displayNearForLabel,ops.displayFarForLabel);
			    param.label={
			        font: this.getFont(ops),
	        		text: point.name||'未定义',
			        horizontalOrigin : VFG.Util.getHorizontalOrigin(ops.horizontalOriginForLabel) ,
			        verticalOrigin : VFG.Util.getVerticalOrigin(ops.verticalOriginForLabel) ,
			        scale: ops.fontScaleForLabel?ops.fontScaleForLabel:1,
			        fillColor :ops.fillColorForLabel?Cesium.Color.fromCssColorString(ops.fillColorForLabel):Cesium.Color.WHITE,
			        outlineWidth : ops.outlineWidthForLabel?ops.outlineWidthForLabel:0,
			        outlineColor:  ops.outlineColorForLabel?Cesium.Color.fromCssColorString(ops.outlineColorForLabel):Cesium.Color.WHITE,
			        pixelOffset: pixelOffset?pixelOffset:new Cesium.Cartesian2(0, 0),
			        showBackground: ops.showBackgroundForLabel&& ops.showBackgroundForLabel==1 ? true:false,
			        backgroundColor: ops.backgroundColorForLabel?Cesium.Color.fromCssColorString(ops.backgroundColorForLabel):new Cesium.Color(0.165, 0.165, 0.165, 0.8),
			        backgroundPadding : backgroundPadding?backgroundPadding:new Cesium.Cartesian2(0, 0),
			        pixelOffsetScaleByDistance :pixelOffsetScaleByDistance?pixelOffsetScaleByDistance:undefined,//偏移量比例
			        scaleByDistance:scaleByDistance?scaleByDistance:undefined, //缩放比例
			        translucencyByDistance:translucencyByDistance?translucencyByDistance:undefined,//半透明度比例            		
			        distanceDisplayCondition :distanceDisplayCondition?distanceDisplayCondition:undefined,
			        style :Cesium.LabelStyle.FILL_AND_OUTLINE,
			        disableDepthTestDistance: Number.POSITIVE_INFINITY 
			    }
			}
			if(ops.showForPoint=='1'){
			    var distanceDisplayCondition =VFG.Util.getDistanceDisplayCondition(ops.displayNearForPoint,ops.displayFarForPoint);
			    var scaleByDistance= VFG.Util.getNearFarScalar(ops.scalarNearForPoint,ops.scalarNearValueForPoint, ops.scalarFarForPoint,ops.scalarFarValueForPoint); 
			    var translucencyByDistance= VFG.Util.getNearFarScalar(ops.translucencyNearForPoint,ops.translucencyNearValueForPoint, ops.translucencyFarForPoint,ops.translucencyFarValueForPoint); 
			    param.point={
					pixelSize : ops.pixelSizeForPoint||5,
					color :ops.colorForPoint?Cesium.Color.fromCssColorString(ops.colorForPoint):Cesium.Color.WHITE,
					outlineColor: ops.outlineColorForPoint? Cesium.Color.fromCssColorString(ops.outlineColorForPoint):Cesium.Color.BLACK,
				    outlineWidth:ops.outlineWidthForPoint?ops.outlineWidthForPoint:0,
			        distanceDisplayCondition : distanceDisplayCondition?distanceDisplayCondition:undefined,
			        scaleByDistance:scaleByDistance?scaleByDistance:undefined, 
			        translucencyByDistance:translucencyByDistance?translucencyByDistance:undefined, 
	        		disableDepthTestDistance: Number.POSITIVE_INFINITY		
				}
			}
			if(ops.showForBillboard=='1'){
				var pixelOffset=VFG.Util.getCartesian2(ops.pixelOffsetXForBillboard*1,ops.pixelOffsetXForBillboard*1);
				var pixelOffsetScaleByDistance= VFG.Util.getNearFarScalar(ops.pixelOffsetScaleNearForBillboard,ops.pixelOffsetScaleNearValueForBillboard, ops.pixelOffsetScaleFarForBillboard,ops.pixelOffsetScaleFarValueForBillboard);
		        var distanceDisplayCondition =VFG.Util.getDistanceDisplayCondition(ops.displayNearForBillboard,ops.displayFarForBillboard);
		        var scaleByDistance= VFG.Util.getNearFarScalar(ops.scalarNearForBillboard,ops.scalarNearValueForBillboard, ops.scalarFarForBillboard,ops.scalarFarValueForBillboard); 
		        var translucencyByDistance =VFG.Util.getNearFarScalar(ops.translucencyNearForBillboard,ops.translucencyNearValueForBillboard, ops.translucencyFarForBillboard,ops.translucencyFarValueForBillboard); 
		        param.billboard={
		            image:ctx+ops.imageForBillboard,
		            width: ops.widthForBillboard,
		            height: ops.heightForBillboard,
		            scale:ops.scaleForBillboard,
		            sizeInMeters: false,
			        pixelOffset: pixelOffset?pixelOffset:new Cesium.Cartesian2(0, ops.heightForBillboard),
		            eyeOffset:new Cesium.Cartesian3(0.0, 0, 0.0),
		            horizontalOrigin : Cesium.HorizontalOrigin.CENTER,
		            verticalOrigin :Cesium.VerticalOrigin.BOTTOM,
			        pixelOffsetScaleByDistance :pixelOffsetScaleByDistance?pixelOffsetScaleByDistance:undefined,//偏移量比例
		            distanceDisplayCondition :distanceDisplayCondition?distanceDisplayCondition:undefined,
		            scaleByDistance:scaleByDistance?scaleByDistance:undefined, //设置距离方位内
		            translucencyByDistance:translucencyByDistance?translucencyByDistance:undefined,
            		disableDepthTestDistance: Number.POSITIVE_INFINITY
		    	}
			}
			return param;
	 }else{
		 return {
			  id: point.id,
	          position: position,
	          code: point.code,
	          point:{
				pixelSize : 5,
				color :Cesium.Color.WHITE,
			 }
		 }
	 }
}


VFG.Point.getFont=function(data){
	var font="";
	if(data.fontSizeForLabel){
		font+=data.fontSizeForLabel+"px "
	}
	if(data.fontWeightForLabel){
		font+=data.fontWeightForLabel+""
	}
	if(data.fontFamilyForLabel){
		font+=data.fontFamilyForLabel+""
	}
	return font
}

VFG.Point.show=function(viewer,param){
	if(this.contain(param.id)){
		var obj=this.Primitives.get(param.id);
		if(obj.render=="1"){
			viewer.entities.getById(id).show=param.show
		}else{
			if(VFG.Point.LabelMap.has(param.id)){
				VFG.Point.LabelMap.get(param.id).show=param.show;
			}
			if(VFG.Point.PointMap.has(param.id)){
				VFG.Point.PointMap.get(param.id).show=param.show;
			}
			if(VFG.Point.BillboardMap.has(param.id)){
				VFG.Point.BillboardMap.get(param.id).show=param.show;
			}
		}
	}
}

VFG.Point.getById=function(viewer,id){
	if(this.contain(id)){
		var obj=this.Primitives.get(id);
		if(obj.render=="1"){
			return viewer.entities.getById(id);
		}else{
			return {
				Label:this.LabelMap.get(id),
				Point:this.PointMap.get(id),
				Billboard:this.BillboardMap.get(id),
			}
		}
	}
}

VFG.Point.removeById=function(viewer,id){
	if(this.contain(id)){
		var obj=this.Primitives.get(id);
		if(obj.render=="1"){
			viewer.entities.removeById(id);
		}else{
			if(VFG.Point.LabelMap.has(id)){
				this.LabelCollection.remove(VFG.Point.LabelMap.get(id));
				this.LabelMap.delete(id);
			}
			if(VFG.Point.PointMap.has(id)){
				this.PointPrimitiveCollection.remove(VFG.Point.PointMap.get(id));
				this.PointMap.delete(id);
				
			}
			if(VFG.Point.BillboardMap.has(id)){
				this.BillboardCollection.remove(VFG.Point.BillboardMap.get(id));
				this.BillboardMap.delete(id)
			}
		}
	}
	this.Primitives.delete(id)
}

VFG.Point.contain=function(id){
	return this.Primitives.has(id)
}

VFG.Point.update=function(viewer,item,ctx){
	var point=item.point;
	if(this.contain(point.id)){
		if(point.render && point.render=="1"){
			var param=this.packageEntity(viewer,item,ctx);
			var entity=viewer.entities.getById(point.id);
			if(entity){
				entity.position=param.position;
				entity.code=param.code||null;
				entity.point=param.point||null;
				entity.label=param.label||null;
				entity.billboard=param.billboard||null;
				entity.position=param.position;
			}
		}else{
			this.addOrUpdatePrimitive(viewer,item,ctx);
		}
	}
}


;
///<jscompress sourcefile="VFGPolygon.js" />
VFG.Polygon=function(){
}
VFG.Polygon.Layers=new Cesium.PrimitiveCollection();
VFG.Polygon.Primitives=new Map();

VFG.Polygon.removeById=function(id){
	if(this.Primitives.has(id)){
		this.Layers.remove(this.Primitives.get(id));
	}
	this.Primitives.delete(id);
}

VFG.Polygon.getById=function(id){
	if(this.Primitives.has(id)){
		return this.Primitives.get(id);
	}
}

VFG.Polygon.add=function(param,url){
	if(!this.Primitives.has(param.polygon.id)){
		var primitive=this.package(param,url);
		this.Layers.add(primitive)
		this.Primitives.set(param.polygon.id,primitive)
	}
}

VFG.Polygon.package=function(param,url){
	var polygon=param.polygon;
	var style=param.style;
	var hierarchy=this.getHierarchy(polygon.points);
	polygon.PrimitiveType="Polygon";
	if(style){
		var distanceDisplayCondition=null
	    if(style.distanceDisplayConditionX*1!=0 || style.distanceDisplayConditionY*1!=0){
			distanceDisplayCondition=new Cesium.DistanceDisplayConditionGeometryInstanceAttribute(style.distanceDisplayConditionX*1, style.distanceDisplayConditionY*1)
	    }
		//普通面
		if("0"==style.displayEffect){
			var perPositionHeight=style.perPositionHeight?style.perPositionHeight*1:false;
			if(perPositionHeight){
				return new Cesium.GroundPrimitive({
			        geometryInstances: new Cesium.GeometryInstance({
			          geometry: new Cesium.PolygonGeometry({
			            polygonHierarchy: hierarchy,
			            stRotation:style.stRotation?style.stRotation*1:0.0,
			          }),
			          id:polygon,
			          attributes : {
		        	     distanceDisplayCondition : distanceDisplayCondition
		        	  },
			        }),
			        appearance: new Cesium.MaterialAppearance({
			            material: this.getMaterial(param.style,url),
			            translucent: false
			        })
			      })
			}else{
				return new Cesium.Primitive({
			        geometryInstances: new Cesium.GeometryInstance({
			          geometry: new Cesium.PolygonGeometry({
						polygonHierarchy: hierarchy,
						stRotation:style.stRotation?style.stRotation*1:0.0,
						perPositionHeight:false,
						height:style.height?style.height*1:0.0,//相对于椭球表面的高度
						extrudedHeight:style.extrudedHeight?style.extrudedHeight*1:0.0,//定多边形的凸出面相对于椭圆表面的高度
						closeTop:style.closeTop?style.closeTop*1:false,
						closeBottom:style.closeBottom?style.closeBottom*1:false,
			          }),
			          id:polygon,
			          attributes : {
		        	     distanceDisplayCondition : distanceDisplayCondition
		        	  },
			        }),
			        appearance: new Cesium.MaterialAppearance({
			            material: this.getMaterial(param.style,url),
			            translucent: false
			        })
		      })
		   }
		}
		else if("1"==style.displayEffect){
			return new Cesium.Primitive({
		        geometryInstances: new Cesium.GeometryInstance({
		          geometry: new Cesium.PolygonGeometry({
					polygonHierarchy: hierarchy,
					stRotation:style.stRotation?style.stRotation*1:0.0,
					perPositionHeight:false,
					height:style.height?style.height*1:0.0,
					extrudedHeight:style.extrudedHeight?style.extrudedHeight*1:0.0,
		          }),
		          id:polygon,
		          attributes : {
	        	     distanceDisplayCondition : distanceDisplayCondition
	        	  },		          
		        }),
		        appearance: new Cesium.MaterialAppearance({
		            material: this.getMaterial(param.style,url),
		            translucent: false,
		        })
	      })
		}
		else if("2"==style.displayEffect){
			return new Cesium.GroundPrimitive({
		        geometryInstances: new Cesium.GeometryInstance({
		          geometry: new Cesium.PolygonGeometry({
		            polygonHierarchy: hierarchy,
		            stRotation:style.stRotation?style.stRotation*1:0.0,
		          }),
		          id:polygon,
		          attributes : {
	        	     distanceDisplayCondition : distanceDisplayCondition
	        	  },		          
		        }),
		        appearance : new Cesium.EllipsoidSurfaceAppearance({
		            material : new Cesium.Material({
		              fabric : {
		                type : 'Water',
		                uniforms : {
		                  normalMap:  url+'/'+style.mapUrl,
		                  frequency: style.frequency?style.frequency*1:1000.0,
		                  animationSpeed: style.speed?style.speed*1:0.01,
		                  amplitude:style.amplitude?style.amplitude*1:10.0,
		                }
		              }
		            }),
		            fragmentShaderSource:'varying vec3 v_positionMC;\nvarying vec3 v_positionEC;\nvarying vec2 v_st;\nvoid main()\n{\nczm_materialInput materialInput;\nvec3 normalEC = normalize(czm_normal3D * czm_geodeticSurfaceNormal(v_positionMC, vec3(0.0), vec3(1.0)));\n#ifdef FACE_FORWARD\nnormalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);\n#endif\nmaterialInput.s = v_st.s;\nmaterialInput.st = v_st;\nmaterialInput.str = vec3(v_st, 0.0);\nmaterialInput.normalEC = normalEC;\nmaterialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(v_positionMC, materialInput.normalEC);\nvec3 positionToEyeEC = -v_positionEC;\nmaterialInput.positionToEyeEC = positionToEyeEC;\nczm_material material = czm_getMaterial(materialInput);\n#ifdef FLAT\ngl_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n#else\ngl_FragColor = czm_phong(normalize(positionToEyeEC), material);\
		            	gl_FragColor.a=0.5;\n#endif\n}\n'//重写shader，修改水面的透明度
		          })
		      })
		}else{
			return new Cesium.GroundPrimitive({
		        geometryInstances: new Cesium.GeometryInstance({
		          geometry: new Cesium.PolygonGeometry({
		            polygonHierarchy: hierarchy,
		            stRotation:style.stRotation?style.stRotation*1:0.0,
		          }),
		          id:polygon,
		          attributes : {
	        	     distanceDisplayCondition : distanceDisplayCondition
	        	  },		          
		        }),
		        appearance: new Cesium.MaterialAppearance({
		            material: this.getMaterial(param.style,url),
		            translucent: false,
		        }),
		        
	       })
		}
	}else{
		return new Cesium.GroundPrimitive({
	        geometryInstances: new Cesium.GeometryInstance({
	          geometry: new Cesium.PolygonGeometry({
	            polygonHierarchy: hierarchy,
	          }),
	          id:polygon
	        }),
	        appearance: new Cesium.MaterialAppearance({
	            material:new Cesium.Material({
				    fabric : {
				        type : 'Color',
				        uniforms : {
				            color : Cesium.Color.RED
				        }
				    }
				}),
	            translucent: false,
	        }),
       })
	}
}

VFG.Polygon.getMaterial=function(style,url){
	if("2"==style.displayEffect){
		return new Cesium.Material({
		    fabric : {
		        type : 'Water',
		        uniforms : {
		            normalMap:  url+'/'+style.mapUrl,
		            frequency: 10000.0,
		            animationSpeed: 1,
		            amplitude: 1.0,
		        }
		    },
		})
	}else{
		if("color"==style.material){
			return new Cesium.Material({
			    fabric : {
			        type : 'Color',
			        uniforms : {
			            color : style.color? Cesium.Color.fromCssColorString(style.color):Cesium.Color.BLACK
			        }
			    }
			})
		}else if("img"==style.material){
			return new Cesium.Material({
			    fabric : {
			        type : 'Image',
			        uniforms : {
			            image : url+'/'+style.mapUrl
			        }
			    }
			})			
		}else{
			return new Cesium.Material({
			    fabric : {
			        type : 'Color',
			        uniforms : {
			            color : style.color? Cesium.Color.fromCssColorString(style.color):Cesium.Color.BLACK
			        }
			    }
			})
		}
	}
}

VFG.Polygon.getHierarchy=function(points){
	if(points){
		var positions=JSON.parse(points);
		if(positions.length>=2){
			var Hierarchy=[];
			for(var i=0;i<positions.length;i++){
				Hierarchy.push(Cesium.Cartesian3.fromDegrees(positions[i].x*1,positions[i].y*1,positions[i].z*1));
			}
			return new Cesium.PolygonHierarchy(Hierarchy);
		}
	}else{
		return [];
	}
}

VFG.Polygon.getPositions=function(points){
	if(points){
		var positions=JSON.parse(points);
		if(positions.length>=2){
			var Hierarchy=[];
			for(var i=0;i<positions.length;i++){
				Hierarchy.push(Cesium.Cartesian3.fromDegrees(positions[i].x*1,positions[i].y*1,positions[i].z*1));
			}
			return Hierarchy;
		}
	}else{
		return [];
	}
}

VFG.Polygon.update=function(param,url){
	var old=this.Primitives.get(param.polygon.id);
	if(old){
		var primitive=this.package(param,url);
		if( old instanceof Cesium.GroundPrimitive && primitive instanceof Cesium.GroundPrimitive){
			old.appearance.material=primitive.appearance.material
			old.geometryInstances=primitive.geometryInstances;
		}
		else if( old instanceof Cesium.Primitive && primitive instanceof Cesium.Primitive){
			old.appearance.material=primitive.appearance.material;
			old.geometryInstances=primitive.geometryInstances;
		}else{
			this.removeById(param.polygon.id);
			this.Layers.add(primitive);
			this.Primitives.set(param.polygon.id,primitive)
		}
	}
}

VFG.Polygon.show=function(param){
	var primitive=this.Primitives.get(param.id);
	if(primitive){
		primitive.show=param.show || true
	}
}
;
///<jscompress sourcefile="VFGPolyline.js" />
VFG.Polyline=function(){
}
VFG.Polyline.Layers=new Cesium.CustomDataSource("polylinesLayer");
VFG.Polyline.Primitives=new Map();

VFG.Polyline.add=function(param,ctx){
	var _this=this;
	_this.Primitives.set(param.polyline.id,param.polyline);
	return this.Layers.entities.add(new Cesium.Entity(_this.packagePolyline(param,ctx)));
}

VFG.Polyline.packagePolyline=function(param,ctx){
	var _this=this;
	var polyline=param.polyline;
	var style=param.style;
	var positions=this.getPositions(polyline.points);
	if(style){
	    var distanceDisplayCondition =VFG.Util.getDistanceDisplayCondition(style.distanceDisplayConditionX,style.distanceDisplayConditionY);
		var material=_this.getMaterial(style,ctx);
		return {
            id:polyline.id,
			name:polyline.name||'',
			code:polyline.code||'',
            polyline:{
		        show: true,
		        positions: positions,
				width : style.width*1,
				loop:style.loop&&style.loop=='1'?true:false,
				clampToGround:style.clampToGround&&style.clampToGround=='1'?true:false,
				material:material?material:Cesium.Color.RED,
				distanceDisplayCondition : distanceDisplayCondition?distanceDisplayCondition:undefined,
				zIndex:polyline.sort||null,
			}
        }
	}else{
		return {
            id:polyline.id,
			name:polyline.name||'',
			code:polyline.code||'',
            polyline: {
                show: true,
                positions:positions,
                material:Cesium.Color.RED,
                width:2,
                clampToGround:true,
            }
        }
	}
}

VFG.Polyline.getMaterial = function(style,ctx){
	var _this=this;
	if(Cesium.defined(style)){
		if(style.materialType=="solid"){
			return (style.color)?Cesium.Color.fromCssColorString(style.color):Cesium.Color.RED;//线条颜色;
		}
		else if(style.materialType=="dash"){
			return new Cesium.PolylineDashMaterialProperty({
				color:(style.color)?Cesium.Color.fromCssColorString(style.color):Cesium.Color.RED,//线条颜色
				gapColor:(style.gapColor)?Cesium.Color.fromCssColorString(style.gapColor):Cesium.Color.WHITE,//间隔颜色
				dashLength:(style.dashLength)?style.dashLength*1:16,//间隔距离
				dashPattern:(style.dashPattern)?style.dashPattern*1:255.0
			})
		}
		else if(style.materialType=="outline"){
			return new Cesium.PolylineOutlineMaterialProperty({
				color:(style.color)?Cesium.Color.fromCssColorString(style.color):Cesium.Color.RED,//线条颜色
				outlineWidth: (style.outlineWidth)?style.outlineWidth*1:5,
				outlineColor:(style.outlineColor)?Cesium.Color.fromCssColorString(style.outlineColor):Cesium.Color.WHITE,//线条颜色
			});
		}
		else if(style.materialType=="glow"){
			return new Cesium.PolylineGlowMaterialProperty({
					color:(style.color)?Cesium.Color.fromCssColorString(style.color):Cesium.Color.RED,//线条颜色
					glowPower: (style.glowPower)?style.glowPower*1:0.5,//发光强度
				});
		}
		else if(style.materialType=="arrow"){
			return new Cesium.PolylineArrowMaterialProperty(
					(style.color)?Cesium.Color.fromCssColorString(style.color):Cesium.Color.RED
			);
		}
		else if(style.materialType=="od"){
			return new Cesium.ODLineMaterial(
					(style.color)?Cesium.Color.fromCssColorString(style.color):Cesium.Color.RED,style.interval?style.interval*1000:20000,style.direction,style.effect,ctx+"/"+style.imageUrl)
		}
		else{
			return Cesium.Color.BLUE;
		}
	}
}

VFG.Polyline.getPositions=function(points){
	if(points){
		var positions;
		if(typeof(points)=='string'){
			positions=JSON.parse(points);
		}else{
			positions=points;
		}
		if(positions.length>=2){
			var Hierarchy=[];
			for(var i=0;i<positions.length;i++){
				Hierarchy.push(Cesium.Cartesian3.fromDegrees(positions[i].x*1,positions[i].y*1,positions[i].z*1));
			}
			return Hierarchy;
		}
	}else{
		return [];
	}
}

VFG.Polyline.contain=function(id){
	return this.Primitives.has(id)
}

VFG.Polyline.getById=function(id){
	if(this.contain(id)){
		var obj=this.Primitives.get(id);
		if(obj.render && obj.render=="1"){
			return this.Layers.entities.getById(id);
		}else{
			return this.Layers.entities.getById(id);
		}
	}
}

VFG.Polyline.removeById=function(id){
	if(this.contain(id)){
		var obj=this.Primitives.get(id);
		if(obj.render && obj.render=="1"){
			return this.Layers.entities.removeById(id);
		}else{
			return this.Layers.entities.removeById(id);
		}
	}
	this.Primitives.delete(id);
}

VFG.Polyline.show=function(param){
	if(this.contain(param.id)){
		var Entity=this.Layers.entities.getById(param.id);
		if(Entity){
			Entity.show=param.show;
		}
	}
}

VFG.Polyline.update=function(param,ctx){
	if(this.contain(param.polyline.id)){
		var option=this.packagePolyline(param,ctx);
		var Entity=this.Layers.entities.getById(param.polyline.id);
		console.log(Entity);
		Entity.id=option.id;
		Entity.name=option.name;
		Entity.code=option.code;
		Entity.polyline=option.polyline;
	}
}



;
///<jscompress sourcefile="WallMaterialProperty.js" />
//定义流动线
function initPolylineTrailLinkMaterialProperty(data) {
    function PolylineTrailLinkMaterialProperty(color, duration) {
        this._definitionChanged = new Cesium.Event();
        this._color = undefined;
        this._colorSubscription = undefined;
        this.color = color;
        this.duration = duration;
        this._time = (new Date()).getTime();
    }
    Object.defineProperties(PolylineTrailLinkMaterialProperty.prototype, {
        isConstant: {
            get: function () {
                return false;
            }
        },
        definitionChanged: {
            get: function () {
                return this._definitionChanged;
            }
        },
        color: Cesium.createPropertyDescriptor('color')
    });
    PolylineTrailLinkMaterialProperty.prototype.getType = function (time) {
        return 'PolylineTrailLink';
    }
    PolylineTrailLinkMaterialProperty.prototype.getValue = function (time, result) {
        if (!Cesium.defined(result)) {
            result = {};
        }
        result.color = Cesium.Property.getValueOrClonedDefault(this._color, time, Cesium.Color.WHITE, result.color);
        result.image = Cesium.Material.PolylineTrailLinkImage;
        result.time = (((new Date()).getTime() - this._time) % this.duration) / this.duration;
        return result;
    }
    PolylineTrailLinkMaterialProperty.prototype.equals = function (other) {
        return this === other || (other instanceof PolylineTrailLinkMaterialProperty && Property.equals(this._color, other._color))
    };
    Cesium.PolylineTrailLinkMaterialProperty = PolylineTrailLinkMaterialProperty;
    Cesium.Material.PolylineTrailLinkType = 'PolylineTrailLink';
    Cesium.Material.PolylineTrailLinkImage = ctx+'/assets/images/colors1.png';//图片
    Cesium.Material.PolylineTrailLinkSource = "czm_material czm_getMaterial(czm_materialInput materialInput)\n\
                                                       {\n\
                                                            czm_material material = czm_getDefaultMaterial(materialInput);\n\
                                                            vec2 st = materialInput.st;\n\
                                                            vec4 colorImage = texture2D(image, vec2(fract(st.s - time), st.t));\n\
                                                            material.alpha = colorImage.a * color.a;\n\
                                                            material.diffuse = (colorImage.rgb+color.rgb)/2.0;\n\
                                                            return material;\n\
                                                        }";
    
/*    "czm_material czm_getMaterial(czm_materialInput materialInput)\n\
    {\n\
        czm_material material = czm_getDefaultMaterial(materialInput);\n\
        vec2 st = materialInput.st;\n\
        vec4 colorImage = texture2D(image, vec2(fract((st.t - time)), st.t));\n\
        vec4 fragColor;\n\
        fragColor.rgb = (colorImage.rgb+color.rgb) / 1.0;\n\
        fragColor = czm_gammaCorrect(fragColor);\n\
        material.alpha = colorImage.a * color.a;\n\
        material.diffuse = (colorImage.rgb+color.rgb)/2.0;\n\
        material.emission = fragColor.rgb;\n\
        return material;\n\
    }";*/
    
    // material.alpha:透明度;material.diffuse：颜色;
    Cesium.Material._materialCache.addMaterial(Cesium.Material.PolylineTrailLinkType, {
        fabric: {
            type: Cesium.Material.PolylineTrailLinkType,
            uniforms: {
                color: new Cesium.Color(1.0, 0.0, 0.0, 0.5),
                image: Cesium.Material.PolylineTrailLinkImage,
                time: 0
            },
            source: Cesium.Material.PolylineTrailLinkSource
        },
        translucent: function (material) {
            return true;
        }
    })
};
///<jscompress sourcefile="CesiumDrag.js" />
/*  *  *  *  *  *  *  *  *  *  *
 *     绘制点
 *  *  *  *  *  *  *  *  *  *  */
!function(e, t) {
	"object" == typeof exports && "object" == typeof module ? module.exports = t(require("Cesium"))
			: "function" == typeof define && define.amd ? define([ "Cesium" ],
					t)
					: "object" == typeof exports ? exports.CesiumDrag = t(require("Cesium"))
							: e.CesiumDrag = t(e.Cesium)
}("undefined" != typeof self ? self : this, function(cesium) {
	function _(viewer, option) {
		this.viewer = viewer;
		this.option = option;
		if(!this.viewer){
			console.log('参数必填！！！');
			return;
		}
		this.cesiumTips=new Cesium.Tip(this.viewer);
		this.noPickEntity=option.primitive;
		this.dragType=option.type|| '';
		this.init();
	}
	_.prototype.init = function() {
		var _self = this;
		var pointDraged;
		var leftDownFlag=false;
		var startPoint;
		var polylinePreviousCoordinates;
		_self.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
		
		//拾取实体
	    _self.handler.setInputAction(function (movement) {
            pointDraged = _self.viewer.scene.pick(movement.position);
            leftDownFlag = true;
            if(_self.dragType){
                if (pointDraged && pointDraged.id && pointDraged.id.type && pointDraged.id.type== _self.dragType) {
                    startPoint = _self.viewer.scene.pickPosition(movement.position);
                    _self.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
                    if(_self.option.LEFT_DOWN){
                    	_self.option.LEFT_DOWN(movement,pointDraged);
                    }
                }
            }else{
                if (pointDraged) {
                    startPoint = _self.viewer.scene.pickPosition(movement.position);
                    _self.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
                }	
            }
        }, Cesium.ScreenSpaceEventType.LEFT_DOWN);
	    
	    _self.handler.setInputAction(function (movement) {
            if(_self.option.LEFT_CLICK){
            	_self.option.LEFT_CLICK(movement);
            }
	    },Cesium.ScreenSpaceEventType.LEFT_CLICK)
	    
	    _self.handler.setInputAction(function (movement) {
            var clickEntiy =  _self.viewer.scene.pick(movement.position);
            if(clickEntiy && clickEntiy.id && clickEntiy.id.id){
                if(_self.option.MIDDLE_CLICK){
                	_self.option.MIDDLE_CLICK(clickEntiy.id.id,clickEntiy);
                }
            }
	    },Cesium.ScreenSpaceEventType.MIDDLE_CLICK)	    
	    
	    _self.handler.setInputAction(function (movement) {
            var clickEntiy =  _self.viewer.scene.pick(movement.position);
            if(clickEntiy && clickEntiy.id && clickEntiy.id.id){
                if(_self.option.LEFT_DOUBLE_CLICK){
                	_self.option.LEFT_DOUBLE_CLICK(clickEntiy.id.id,clickEntiy);
                }
            }
	    },Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
	    

        // Release plane on mouse up
	    _self.handler.setInputAction(function () {
            if (leftDownFlag === true && pointDraged != null && (
            		(pointDraged.id && (pointDraged.id.point ||pointDraged.id.billboard || pointDraged.id.label ||pointDraged.id.model )) ||
            	    (pointDraged.primitive && pointDraged.primitive.gltf)
            )) {
            	if(_self.option.LEFT_UP){
            		_self.option.LEFT_UP(pointDraged);
            	}
            }
            leftDownFlag = false;
            pointDraged = null;
            _self.viewer.scene.screenSpaceCameraController.enableInputs = true;
            _self.viewer.scene.screenSpaceCameraController.enableRotate = true;//锁定相机
            
        }, Cesium.ScreenSpaceEventType.LEFT_UP);
	    
	    
        // Update plane on mouse move
	    _self.handler.setInputAction(function (movement) {
            if (leftDownFlag === true && pointDraged != null && (
            		(pointDraged.id && (pointDraged.id.point ||pointDraged.id.billboard || pointDraged.id.label ||pointDraged.id.model )) ||
            	    (pointDraged.primitive && pointDraged.primitive.gltf)
            )) {
    	    	_self.cesiumTips.showAt(movement.endPosition, `<div class="con" style="color: white;">拖拽中！</div>`);
    	    	var cartesian3 =VFG.Util.getScreenToC3(_self.viewer,movement.endPosition,_self.noPickEntity);
                if(_self.option.mouseMove && cartesian3){
                	if(pointDraged.id.id){
                		_self.option.mouseMove(pointDraged.id.id,cartesian3);
                	}
                	else if(pointDraged.primitive.gltf){
                		_self.option.mouseMove(pointDraged.id,cartesian3);
                	}
                }
                
            }else{
    	    	_self.cesiumTips.showAt(movement.endPosition, `<div class="con" style="color: white;">按下鼠标左键拖拽，右键退出！</div>`);
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	    
	    //右键点击操作
	    _self.handler.setInputAction(function (click) {
	    	_self.destroy();
	    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
	};
	_.prototype.destroy = function() {
        if( this.option.end){
        	this.option.end();
        };
        if( this.handler){
        	this.handler.destroy();
        	this.handler = null;
        };
        if( this.cesiumTips){
        	this.cesiumTips.destroy();
        	this.cesiumTips=null;
        };
		delete this.ops,
		delete this.cesiumTips,
		delete this.handler;
		return Cesium.destroyObject(this);
	};
	cesium.Drag = _;
})

;
///<jscompress sourcefile="CesiumDraw.js" />
/*  *  *  *  *  *  *  *  *  *  *
 *     绘制点
 *  *  *  *  *  *  *  *  *  *  */
!function(e, t) {
	"object" == typeof exports && "object" == typeof module ? module.exports = t(require("Cesium"))
			: "function" == typeof define && define.amd ? define([ "Cesium" ],
					t)
					: "object" == typeof exports ? exports.CesiumDrawPoint = t(require("Cesium"))
							: e.CesiumDrawPoint = t(e.Cesium)
}("undefined" != typeof self ? self : this, function(cesium) {
	function _(viewer, option) {
		this.viewer = viewer;
		this.option = option;
		if(!this.viewer){
			console.log('参数必填！！！');
			return;
		}
		this.cesiumTips=new Cesium.Tip(this.viewer);
		this.init();
	}
	_.prototype.init = function() {
		var _self = this;
		_self.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
	    //左键点击操作
	    _self.handler.setInputAction(function (click) {
	        var cartesian3 =VFG.Util.getScreenToC3(_self.viewer,click.position,_self.primitive);
	        if (Cesium.defined(cartesian3)){
		        if( _self.option.pick){
		        	 _self.option.pick(cartesian3);
		        }
	        }
	    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
	    
	    //鼠标移动事件
	    _self.handler.setInputAction(function (movement) {
	    	_self.cesiumTips.showAt(movement.endPosition, `<div class="con" style="color: white;">点击添加，右键退出！</div>`);
	    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

	    //右键点击操作
	    _self.handler.setInputAction(function (click) {
	    	_self.destroy();

	    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
	};
	_.prototype.destroy = function() {
        if( this.option.end){
        	this.option.end();
        };
        if( this.handler){
        	this.handler.destroy();
        	this.handler = null;
        };
        if( this.cesiumTips){
        	this.cesiumTips.destroy();
        	this.cesiumTips=null;
        };
		delete this.ops,
		delete this.cesiumTips,
		delete this.handler;
		return Cesium.destroyObject(this);
	};
	cesium.DrawPoint = _;
})

/*  *  *  *  *  *  *  *  *  *  *
 *     绘制线 
 *  *  *  *  *  *  *  *  *  *  */
!function(e, t) {
	"object" == typeof exports && "object" == typeof module ? module.exports = t(require("Cesium"))
			: "function" == typeof define && define.amd ? define([ "Cesium" ],
					t)
					: "object" == typeof exports ? exports.CesiumDrawLine = t(require("Cesium"))
							: e.CesiumDrawLine = t(e.Cesium)
}("undefined" != typeof self ? self : this, function(cesium) {
	function _(viewer, option) {
		this.viewer = viewer;
		this.option = option;
		if(!this.viewer){
			console.log('参数必填！！！');
			return;
		}
		//坐标存储
		this.cesiumTips=new Cesium.Tip(this.viewer);
		this.positions= [];
		this.primitive=undefined;
		this.init();
	}
	_.prototype.init = function() {
		var _self = this;
		_self.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
		//左键点击操作
	    _self.handler.setInputAction(function (movement) {
	        var cartesian3 =VFG.Util.getScreenToC3(_self.viewer,movement.position,_self.primitive);
	        if (Cesium.defined(cartesian3)){
	            if (_self.positions.length == 0) {
	            	_self.positions.push(cartesian3.clone());
	            }
                if(_self.option.leftClick){
                	_self.option.leftClick(cartesian3);
                }
                _self.positions.push(cartesian3);
	        }
	    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
	    
	    //鼠标移动事件
	    _self.handler.setInputAction(function (movement) {
	    	_self.cesiumTips.showAt(movement.endPosition, `<div class="con" style="color: white;">单击开始绘制，右键退出！</div>`);
	    	var cartesian3 =VFG.Util.getScreenToC3(_self.viewer,movement.endPosition,_self.primitive);
            if (_self.positions.length >= 2) {
            	if(Cesium.defined(cartesian3)){
                    _self.positions.pop();
                //    cartesian3.y += (1 + Math.random());
                    _self.positions.push(cartesian3);
                    if(_self.option.mouseMove){
                    	_self.option.mouseMove(_self.positions);
                    }
            	}

            }
	    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

	    //右键点击操作
	    _self.handler.setInputAction(function (click) {
	    	if( _self.positions){
    		  _self.positions.pop();
              if(_self.option.mouseMove){
              	_self.option.mouseMove(_self.positions);
              }
	    	}
	    	_self.destroy();
	    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
	};
	_.prototype.destroy = function() {
        if( this.option.end){
        	this.option.end();
        };
        if( this.handler){
        	this.handler.destroy();
        	this.handler = null;
        };
        if( this.cesiumTips){
        	this.cesiumTips.destroy();
        	this.cesiumTips=null;
        };
		delete this.ops,
		delete this.cesiumTips,
		delete this.handler;
		return Cesium.destroyObject(this);
	};
	cesium.DrawLine = _;
})

/**
 * 绘制多边形
 */
!function(e, t) {
	"object" == typeof exports && "object" == typeof module ? module.exports = t(require("Cesium"))
			: "function" == typeof define && define.amd ? define([ "Cesium" ],
					t)
					: "object" == typeof exports ? exports.CesiumDrawPolygon = t(require("Cesium"))
							: e.CesiumDrawPolygon = t(e.Cesium)
}("undefined" != typeof self ? self : this, function(cesium) {
	function _(viewer, option) {
		this.viewer = viewer;
		this.option = option;
		if(!this.viewer){
			console.log('参数必填！！！');
			return;
		}
		//坐标存储
		this.cesiumTips=new Cesium.Tip(this.viewer);
		this.positions= [];
		this.primitive=undefined;
		this.init();
	}
	_.prototype.init = function() {
		var _self = this;
		_self.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
		//左键点击操作
	    _self.handler.setInputAction(function (movement) {
	        var cartesian3 =VFG.Util.getScreenToC3(_self.viewer,movement.position,_self.primitive);
	        if (Cesium.defined(cartesian3)){
	            if (_self.positions.length == 0) {
	            	_self.positions.push(cartesian3.clone());
	            }
                if(_self.option.leftClick){
                	_self.option.leftClick(cartesian3);
                }
                _self.positions.push(cartesian3);
	        }
	        
	    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
	    
	    //鼠标移动事件
	    _self.handler.setInputAction(function (movement) {
	    	_self.cesiumTips.showAt(movement.endPosition, `<div class="con" style="color: white;">单击开始绘制，右键退出！</div>`);
	    	var cartesian3 =VFG.Util.getScreenToC3(_self.viewer,movement.endPosition,_self.primitive);
            if (_self.positions.length >= 2) {
            	if(Cesium.defined(cartesian3)){
                    _self.positions.pop();
                    _self.positions.push(cartesian3);
                    if(_self.option.mouseMove){
                    	_self.option.mouseMove(_self.positions);
                    }
            	}

            }
	    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

	    //右键点击操作
	    _self.handler.setInputAction(function (click) {
	    	if( _self.positions){
	    		  _self.positions.pop();
	              if(_self.option.mouseMove){
	              	_self.option.mouseMove(_self.positions);
	              }
		    	}
	    	_self.destroy();
	    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
	};
	_.prototype.destroy = function() {
        if( this.option.end){
        	this.option.end();
        };
        if( this.handler){
        	this.handler.destroy();
        	this.handler = null;
        };
        if( this.cesiumTips){
        	this.cesiumTips.destroy();
        	this.cesiumTips=null;
        };
		delete this.ops,
		delete this.cesiumTips,
		delete this.handler;
		return Cesium.destroyObject(this);
	};
	cesium.DrawPolygon = _;
})

/**
 * 绘制模型
 */
!function(e, t) {
	"object" == typeof exports && "object" == typeof module ? module.exports = t(require("Cesium"))
			: "function" == typeof define && define.amd ? define([ "Cesium" ],
					t)
					: "object" == typeof exports ? exports.CesiumDrawModel = t(require("Cesium"))
							: e.CesiumDrawModel = t(e.Cesium)
}("undefined" != typeof self ? self : this, function(cesium) {
	function _(viewer, option) {
		this.viewer = viewer;
		this.option = option;
		if(!this.viewer){
			console.log('参数必填！！！');
			return;
		}
		//坐标存储
		this.cesiumTips=new Cesium.Tip(this.viewer);
		this.primitive=undefined;
		this.init();
	}
	_.prototype.init = function() {
		var _self = this;
		_self.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
		//左键点击操作
	    _self.handler.setInputAction(function (movement) {
	        var cartesian3 =VFG.Util.getScreenToC3(_self.viewer,movement.position);
	        if (Cesium.defined(cartesian3)){
                if(_self.option.leftClick){
                	_self.option.leftClick(cartesian3);
                }
	        }
	    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
	    
	    //鼠标移动事件
	    _self.handler.setInputAction(function (movement) {
	    	_self.cesiumTips.showAt(movement.endPosition, `<div class="con" style="color: white;">单击确定模型位置，右键退出！</div>`);
	    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

	    //右键点击操作
	    _self.handler.setInputAction(function (click) {
	    	_self.destroy();
	    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
	};
	_.prototype.destroy = function() {
        if( this.option.end){
        	this.option.end();
        };
        if( this.handler){
        	this.handler.destroy();
        	this.handler = null;
        };
        if( this.cesiumTips){
        	this.cesiumTips.destroy();
        	this.cesiumTips=null;
        };
		delete this.ops,
		delete this.cesiumTips,
		delete this.handler;
		return Cesium.destroyObject(this);
	};
	cesium.DrawModel = _;
})
/**
 * 绘制投影
 */
!function(e, t) {
	"object" == typeof exports && "object" == typeof module ? module.exports = t(require("Cesium"))
			: "function" == typeof define && define.amd ? define([ "Cesium" ],
					t)
					: "object" == typeof exports ? exports.Box  = t(require("Cesium"))
							: e.CesiumAnalysi = t(e.Cesium)
}("undefined" != typeof self ? self : this, function(cesium) {
	function _(viewer, option) {
		this.viewer = viewer;
		this.option = option;
		this.cesiumTips=new Cesium.Tip(this.viewer);
		this.init();
	}
	_.prototype.init = function() {
		var _self = this;
		_self.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
		_self.cesiumTips=new Cesium.Tip(_self.viewer);
		var msg= `<div class="con" style="color: white;">单击确定相机位置，右击退出</div>`;
		var positions=[];
		var isEnd=false;
		//鼠标左键
		_self.handler.setInputAction(function (movement) { 
	        var cartesian =VFG.Util.getScreenToC3(_self.viewer,movement.position);
	        if(Cesium.defined(cartesian)){
	            if(positions.length === 0){
	            	msg= `<div class="con" style="color: white;">单击确定视点位置，右击退出</div>`;
	            	positions.push(cartesian.clone());
	            	positions.push(cartesian);
	            	isEnd=true;
	            }else{
	            	positions.pop();
	            	positions.push(cartesian);
	                if(_self.option.END){
	                	_self.option.END(positions);
	                }
	                _self.destroy();
	            }
	        }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
		//鼠标移动
		_self.handler.setInputAction(function(movement) {
	    	var cartesian =VFG.Util.getScreenToC3(_self.viewer,movement.endPosition);
	    	_self.cesiumTips.showAt(movement.endPosition,msg);
			if (positions.length >= 2) {
				if (!Cesium.defined(_self.polyLine)) {
					_self.polyLine =_self.viewer.entities.add({
				        polyline : {
				            positions :new Cesium.CallbackProperty(function() {
								return positions;
							}, false),
				            width : 10,
				            arcType : Cesium.ArcType.NONE,
				            material : new Cesium.PolylineArrowMaterialProperty(Cesium.Color.PURPLE)
				        }
				    });
				} else {
					if (cartesian != undefined) {
						positions.pop();
						positions.push(cartesian);
					}
				}
			}
		}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
		
		//鼠标右键
		_self.handler.setInputAction(function(movement) {
            if(_self.option.END){
            	_self.option.END(positions);
            }
			_self.destroy();
		}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
	};
	_.prototype.destroy = function() {
        if( this.option.end){
        	this.option.end();
        };
        if( this.handler){
        	this.handler.destroy();
        	this.handler = null;
        };
        if( this.cesiumTips){
        	this.cesiumTips.destroy();
        	this.cesiumTips=null;
        };
        if( this.polyLine){
        	this.viewer.entities.remove(this.polyLine);
        	this.polyLine=null;
        };
        delete this.option,
		delete this.cesiumTips,
		delete this.handler;
		return Cesium.destroyObject(this);
	};
	cesium.DrawVideoShed3D = _;
})

/**
 * 绘制漫游路线
 */
!function(e, t) {
	"object" == typeof exports && "object" == typeof module ? module.exports = t(require("Cesium"))
			: "function" == typeof define && define.amd ? define([ "Cesium" ],
					t)
					: "object" == typeof exports ? exports.DrawRoam  = t(require("Cesium"))
							: e.CesiumDrawRoam = t(e.Cesium)
}("undefined" != typeof self ? self : this, function(cesium) {
	function _(viewer, option) {
		this.viewer = viewer;
		this.option = option;
		this.cesiumTips=new Cesium.Tip(this.viewer);
		this.init();
	}
	_.prototype.init = function() {
		var _self = this;
		_self.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
		_self.cesiumTips=new Cesium.Tip(_self.viewer);
		var msg= `<div class="con" style="color: white;">单击添加漫游点，右击退出</div>`;
		var positions=[];
		var LnLas=[];
		var isEnd=false;
		//鼠标左键
		_self.handler.setInputAction(function (movement) { 
	        var cartesian =VFG.Util.getScreenToC3(_self.viewer,movement.position);
	        if(Cesium.defined(cartesian)){
	            if(positions.length === 0){
	            	positions.push(cartesian.clone());
	            	LnLas.push(VFG.Util.getLnLaFormC3(_self.viewer,cartesian));
	            }
	            positions.push(cartesian);
	            LnLas.push(VFG.Util.getLnLaFormC3(_self.viewer,cartesian));
	        }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
		//鼠标移动
		_self.handler.setInputAction(function(movement) {
	    	var cartesian =VFG.Util.getScreenToC3(_self.viewer,movement.endPosition);
	    	_self.cesiumTips.showAt(movement.endPosition,msg);
			if (positions.length >= 2) {
				if (!Cesium.defined(_self.polyLine)) {
					_self.polyLine =_self.viewer.entities.add({
				        polyline : {
				            positions :new Cesium.CallbackProperty(function() {
								return positions;
							}, false),
				            width : 3,
				    		clampToGround:true,
				            material : Cesium.Color.RED
				        }
				    });
				} else {
					if (cartesian != undefined) {
						positions.pop();
						positions.push(cartesian);
						LnLas.pop();
						LnLas.push(VFG.Util.getLnLaFormC3(_self.viewer,cartesian));
					}
				}
			}
		}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
		
		//鼠标右键
		_self.handler.setInputAction(function(movement) {
			positions.pop();
			LnLas.pop();
			if(_self.option.END){
            	_self.option.END(positions,LnLas);
            }
			_self.destroy();
		}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
	};
	_.prototype.destroy = function() {
        if( this.option.end){
        	this.option.end();
        };
        if( this.handler){
        	this.handler.destroy();
        	this.handler = null;
        };
        if( this.cesiumTips){
        	this.cesiumTips.destroy();
        	this.cesiumTips=null;
        };
        if( this.polyLine){
        	this.viewer.entities.remove(this.polyLine);
        	this.polyLine=null;
        };
        delete this.option,
		delete this.cesiumTips,
		delete this.handler;
		return Cesium.destroyObject(this);
	};
	cesium.DrawRoam = _;
});
///<jscompress sourcefile="CesiumPick.js" />
!function(e, t) {
	"object" == typeof exports && "object" == typeof module ? module.exports = t(require("Cesium"))
			: "function" == typeof define && define.amd ? define([ "Cesium" ],
					t)
					: "object" == typeof exports ? exports.CesiumDrag = t(require("Cesium"))
							: e.CesiumPick = t(e.Cesium)
}("undefined" != typeof self ? self : this, function(cesium) {
	function _(viewer, option) {
		this.viewer = viewer;
		this.option = option;
		if(!this.viewer){
			console.log('参数必填！！！');
			return;
		}
		this.cesiumTips=new Cesium.Tip(this.viewer);
		this.noPickEntity=option.primitive;
		this.dragType=option.type|| '';
		this.init();
	}
	_.prototype.init = function() {
		var _self = this;
		_self.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
		//拾取实体
	    _self.handler.setInputAction(function (movement) {
            if(_self.option.LEFT_CLICK){
            	_self.option.LEFT_CLICK(movement);
            }
	    },Cesium.ScreenSpaceEventType.LEFT_CLICK)
	    
        // Update plane on mouse move
	    _self.handler.setInputAction(function (movement) {
	    	_self.cesiumTips.showAt(movement.endPosition, `<div class="con" style="color: white;">鼠标单击拾取位置，右键结束！</div>`);
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	    
	    //右键点击操作
	    _self.handler.setInputAction(function (movement) {
            if(_self.option.RIGHT_CLICK){
            	_self.option.RIGHT_CLICK(movement);
            }
            _self.destroy();
	    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
	};
	_.prototype.destroy = function() {
        if( this.option.end){
        	this.option.end();
        };
        if( this.handler){
        	this.handler.destroy();
        	this.handler = null;
        };
        if( this.cesiumTips){
        	this.cesiumTips.destroy();
        	this.cesiumTips=null;
        };
		delete this.ops,
		delete this.cesiumTips,
		delete this.handler;
		return Cesium.destroyObject(this);
	};
	cesium.Pick = _;
})

;
///<jscompress sourcefile="CesiumTip.js" />
/*  *  *  *  *  *  *  *  *  *  *
 *     Tip      *
 *  *  *  *  *  *  *  *  *  *  */
!function(e, t) {
	"object" == typeof exports && "object" == typeof module ? module.exports = t(require("Cesium"))
			: "function" == typeof define && define.amd ? define([ "Cesium" ],
					t)
					: "object" == typeof exports ? exports.CesiumMQTT = t(require("Cesium"))
							: e.CesiumMQTT = t(e.Cesium)
}("undefined" != typeof self ? self : this, function(cesium) {
	function _(viewer, options) {
		this.viewer = viewer;
		this.options = options;
		this.frameDiv=this.viewer.cesiumWidget.container;
		this.isInit=false;
		this.init();
	}
	_.prototype.init = function() {
		var _self = this;
	    if (_self.isInit) { return; }
	    var div = document.createElement('DIV');
	    div.className = "toolTip-left";
	    var title = document.createElement('DIV');
	    title.className = "tooltipdiv-inner";
	    div.appendChild(title);
	    _self._div = div;
	    _self._title = title;
	    _self.frameDiv.appendChild(div);
	    _self.isInit = true;
	};
	_.prototype.setVisible = function(visible) {
		var _self = this;
	    if (!_self.isInit) { return; }
	    _self._div.style.display = visible ? 'block' : 'none';
	};
	_.prototype.showAt = function (position, message) {
		var _self = this;
	    if (!_self.isInit) { return; }
	    if (position && message) {
	    	_self.setVisible(true);
	    	_self._title.innerHTML = message;
	    	_self._div.style.position = "absolute"
	    	_self._div.style.left = position.x + 20 + "px";
	    	_self._div.style.top = (position.y - this._div.clientHeight/2) + "px";
	    }
    };
	_.prototype.destroy = function() {
		var _self = this;
		if( _self._div){
			$( _self._div).remove();
		}
		if( _self._title){
			$( _self._title).remove();
		}
		return Cesium.destroyObject(this);
	};
	cesium.Tip = _;
});
///<jscompress sourcefile="CesiumVFGWin.js" />
!function(e, t) {
	"object" == typeof exports && "object" == typeof module ? module.exports = t(require("Cesium"))
			: "function" == typeof define && define.amd ? define([ "Cesium" ],
					t)
					: "object" == typeof exports ? exports.CesiumVFGWin = t(require("Cesium"))
							: e.CesiumVFGWin = t(e.Cesium)
}("undefined" != typeof self ? self : this, function(cesium) {
	function _(viewer,option) {
		this.viewer = viewer;
		this.option = Cesium.defaultValue(option, Cesium.defaultValue.EMPTY_OBJECT);
		this.position=option.position;
		this.layerIndex=option.index;
		this.layero=option.layero;
		this.width;
		this.height;
		this.init();
	}
	_.prototype.init= function() {
		var _this=this;
		var cartesian2=Cesium.SceneTransforms.wgs84ToWindowCoordinates(_this.viewer.scene, _this.position);
		if (Cesium.defined(cartesian2)){
			_this.width=(layui.$(_this.layero).css('width').replace('px','')*1)/2;
			_this.height=(layui.$(_this.layero).css('height').replace('px','')*1)+30;
			layer.style(_this.layerIndex, {
				left:(cartesian2.x+200-_this.width)+'px',
				top:(cartesian2.y-_this.height)+'px'
			});
		}
    	_this.event=function(){
    		var cartesian2=Cesium.SceneTransforms.wgs84ToWindowCoordinates(_this.viewer.scene, _this.position);
    		if (Cesium.defined(cartesian2)){
        		layer.style(_this.layerIndex, {
    				left:(cartesian2.x+200-_this.width)+'px',
    				top:(cartesian2.y-_this.height)+'px'
        		});
    		}
    	}
    	_this.viewer.scene.postRender.addEventListener(_this.event);
	};
	_.prototype.destroy = function() {
		var _this = this;
		if(_this.event){
			_this.viewer.scene.postRender.removeEventListener(_this.event);
		}
		delete this.viewer,
		delete this.option,
		delete this.position,
		delete this.layerIndex;
		delete this.layero;
		delete this.width;
		delete this.height;
		return Cesium.destroyObject(this);
	};
	cesium.VFGWin= _;
});
///<jscompress sourcefile="VFGAroundPoint.js" />
//    		new VFG.AroundPoint(viewer,{
//    			position:{x:103.38398032314626,y:23.368851347473854,z:1350},
//    			pitch:0,
//    			distance:2000
//    		});
VFG.AroundPoint=function(viewer,option){
	this.viewer=viewer;
	this.option=option;
	this.position=option.position;
	this.distance=option.distance?option.distance*1:150000;//垂直高度
	this.angle=option.angle?option.angle*1:360/30;
	this.pitch=option.pitch?Cesium.Math.toRadians(option.pitch*1):-10;
	this.time=option.time?option.time*1:1000;
	this.multiplier=option.multiplier?option.multiplier*1:1;
	
	var _this=this;
	this.viewer.camera.flyTo({
        destination :  Cesium.Cartesian3.fromDegrees(_this.position.x, _this.position.y, _this.position.z), // 设置位置
        complete: function () {
            _this.init();
        },
        cancle: function () {
        },
       // pitchAdjustHeight: -90, // 如果摄像机飞越高于该值，则调整俯仰俯仰的俯仰角度，并将地球保持在视口中。
       // maximumHeight:5000, // 相机最大飞行高度
       // flyOverLongitude: 100, // 如果到达目的地有2种方式，设置具体值后会强制选择方向飞过这个经度
    });
}

VFG.AroundPoint.prototype.init = function() {
	var _this = this;
    var startTime=Cesium.JulianDate.fromDate(new Date());
    var stopTime=Cesium.JulianDate.addSeconds(startTime, _this.time, new Cesium.JulianDate());             
    _this.viewer.clock.startTime=startTime.clone();
    _this.viewer.clock.stopTime =stopTime.clone(); 
    _this.viewer.clock.currentTime = startTime.clone(); // 当前时间
    _this.viewer.clock.multiplier = _this.multiplier;
    _this.viewer.clock.clockRange = Cesium.ClockRange.CLAMPED; // 行为方式
    _this.viewer.clock.clockStep = Cesium.ClockStep.SYSTEM_CLOCK; // 时钟设置为当前系统时间; 忽略所有其他设置。
    var initialHeading = _this.viewer.camera.heading;
    _this.renderListener = function TimeExecution() {
        var delTime = Cesium.JulianDate.secondsDifference(_this.viewer.clock.currentTime, _this.viewer.clock.startTime);
        var heading = Cesium.Math.toRadians(delTime * _this.angle) + initialHeading;
        _this.viewer.scene.camera.setView({
            destination : Cesium.Cartesian3.fromDegrees(_this.position.x, _this.position.y, _this.position.z), // 点的坐标
                orientation: {
                    heading : heading,
                    pitch :  _this.pitch,
                }
            });
        _this.viewer.scene.camera.moveBackward(_this.distance);
        if (Cesium.JulianDate.compare(_this.viewer.clock.currentTime, _this.viewer.clock.stopTime) >= 0) {
        	_this.viewer.clock.onTick.removeEventListener(_this.renderListener);
        }
    };
    _this.viewer.clock.onTick.addEventListener(_this.renderListener);
};

VFG.AroundPoint.prototype.getClockRange=function(clockRange) {
	if(clockRange=='CLAMPED'){
		return Cesium.ClockRange.CLAMPED;
	}
	else if(clockRange=='LOOP_STOP'){
		return Cesium.ClockRange.LOOP_STOP;
	}
	else if(clockRange=='UNBOUNDED'){
		return Cesium.ClockRange.UNBOUNDED;
	}else{
		return Cesium.ClockRange.LOOP_STOP;
	}
}

VFG.AroundPoint.prototype.pauseOrContinue = function(state) {
    this.viewer.clock.shouldAnimate = state;
}

VFG.AroundPoint.prototype.changeSpeed = function(value) {
	this.multiplier= value;
    this.viewer.clock.multiplier = value;
}

VFG.AroundPoint.prototype.destroy = function() {
	if(this.renderListener){
		this.viewer.clock.onTick.removeEventListener(this.renderListener);
	}
    delete this.option,
    delete this.viewer
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="VFGCircleScan.js" />
/*new VFG.CircleScan(viewer,{
	x:103.38398032314626,
	y:23.368851347473854,
	color:'rgb(255,255,44)',
	radius:1000,
	interval:4000,
})*/

VFG.CircleScan=function(viewer,option){
	if(!viewer){
		return;
	}
	if(!option){
		return;
	}
	this.viewer=viewer;
	this.option=option;
	this.init();
}
VFG.CircleScan.prototype.init=function(){
	var _this=this;
	this.viewer.scene.globe.depthTestAgainstTerrain = true; 
    var cartographicCenter = new Cesium.Cartographic(Cesium.Math.toRadians(this.option.x*1), Cesium.Math.toRadians(this.option.y*1),0); //中心位子
    var maxRadius=this.option.radius*1;
    var duration=this.option.interval*1;
    var scanColor=Cesium.Color.fromCssColorString(this.option.color);
    var ScanSegmentShader =
        "uniform sampler2D colorTexture;\n" +
        "uniform sampler2D depthTexture;\n" +
        "varying vec2 v_textureCoordinates;\n" +
        "uniform vec4 u_scanCenterEC;\n" +
        "uniform vec3 u_scanPlaneNormalEC;\n" +
        "uniform float u_radius;\n" +
        "uniform vec4 u_scanColor;\n" +
        "vec4 toEye(in vec2 uv, in float depth)\n" +
        " {\n" +
        " vec2 xy = vec2((uv.x * 2.0 - 1.0),(uv.y * 2.0 - 1.0));\n" +
        " vec4 posInCamera =czm_inverseProjection * vec4(xy, depth, 1.0);\n" +
        " posInCamera =posInCamera / posInCamera.w;\n" +
        " return posInCamera;\n" +
        " }\n" +
        "vec3 pointProjectOnPlane(in vec3 planeNormal, in vec3 planeOrigin, in vec3 point)\n" +
        "{\n" +
        "vec3 v01 = point -planeOrigin;\n" +
        "float d = dot(planeNormal, v01) ;\n" +
        "return (point - planeNormal * d);\n" +
        "}\n" +
        "float getDepth(in vec4 depth)\n" +
        "{\n" +
        "float z_window = czm_unpackDepth(depth);\n" +
        "z_window = czm_reverseLogDepth(z_window);\n" +
        "float n_range = czm_depthRange.near;\n" +
        "float f_range = czm_depthRange.far;\n" +
        "return (2.0 * z_window - n_range - f_range) / (f_range - n_range);\n" +
        "}\n" +
        "void main()\n" +
        "{\n" +
        "gl_FragColor = texture2D(colorTexture, v_textureCoordinates);\n" +
        "float depth = getDepth( texture2D(depthTexture, v_textureCoordinates));\n" +
        "vec4 viewPos = toEye(v_textureCoordinates, depth);\n" +
        "vec3 prjOnPlane = pointProjectOnPlane(u_scanPlaneNormalEC.xyz, u_scanCenterEC.xyz, viewPos.xyz);\n" +
        "float dis = length(prjOnPlane.xyz - u_scanCenterEC.xyz);\n" +
        "if(dis < u_radius)\n" +
        "{\n" +
        "float f = 1.0 -abs(u_radius - dis) / u_radius;\n" +
        "f = pow(f, 4.0);\n" +
        "gl_FragColor = mix(gl_FragColor, u_scanColor, f);\n" +
        "}\n" +
        "}\n";

    var _Cartesian3Center = Cesium.Cartographic.toCartesian(cartographicCenter);
    var _Cartesian4Center = new Cesium.Cartesian4(_Cartesian3Center.x, _Cartesian3Center.y, _Cartesian3Center.z, 1);
    var _CartographicCenter1 = new Cesium.Cartographic(cartographicCenter.longitude, cartographicCenter.latitude, cartographicCenter.height + 500);
    var _Cartesian3Center1 = Cesium.Cartographic.toCartesian(_CartographicCenter1);
    var _Cartesian4Center1 = new Cesium.Cartesian4(_Cartesian3Center1.x, _Cartesian3Center1.y, _Cartesian3Center1.z, 1);
    var _time = (new Date()).getTime();
    var _scratchCartesian4Center = new Cesium.Cartesian4();
    var _scratchCartesian4Center1 = new Cesium.Cartesian4();
    var _scratchCartesian3Normal = new Cesium.Cartesian3();
    _this.scanPostStage = new Cesium.PostProcessStage({
        fragmentShader: ScanSegmentShader,
        uniforms: {
            u_scanCenterEC: function () {
                return Cesium.Matrix4.multiplyByVector(viewer.camera._viewMatrix, _Cartesian4Center, _scratchCartesian4Center);
            },
            u_scanPlaneNormalEC: function () {
                var temp = Cesium.Matrix4.multiplyByVector(viewer.camera._viewMatrix, _Cartesian4Center, _scratchCartesian4Center);
                var temp1 = Cesium.Matrix4.multiplyByVector(viewer.camera._viewMatrix, _Cartesian4Center1, _scratchCartesian4Center1);
                _scratchCartesian3Normal.x = temp1.x - temp.x;
                _scratchCartesian3Normal.y = temp1.y - temp.y;
                _scratchCartesian3Normal.z = temp1.z - temp.z;
                Cesium.Cartesian3.normalize(_scratchCartesian3Normal, _scratchCartesian3Normal);
                return _scratchCartesian3Normal;

            },
            u_radius: function () {
                return maxRadius * (((new Date()).getTime() - _time) % duration) / duration;
            },
            u_scanColor: scanColor
        }
    });
    _this.viewer.scene.postProcessStages.add(_this.scanPostStage);
}
VFG.CircleScan.prototype.destroy = function() {
	if(this.scanPostStage){
        this.viewer.scene.postProcessStages.remove(this.scanPostStage);
	}
    delete this.option,
    delete this.scanPostStage,
    delete this.viewer
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="VFGClassification.js" />
/**
 * 定义分类
 */
VFG.ClassificationPrimitive=function(option){
	this.option = Cesium.defaultValue(option, Cesium.defaultValue.EMPTY_OBJECT);
	if (!option) {
		console.log('参数必填!');
	}
	this.id=option.id||VFG.Util.getUuid();
	this.name=option.name||'未命名';
	this.isView=option.isView||'1';
	this.position=option.position;
	this.rotation=option.rotation;
	this.dimensions=option.dimensions;
	this.normalColor=option.normalColor? Cesium.Color.fromCssColorString(option.normalColor) :Cesium.Color.fromCssColorString('rgba(255,3,244,0.5)');
	this.hoverColor=option.hoverColor? Cesium.Color.fromCssColorString(option.hoverColor) :Cesium.Color.fromCssColorString('rgba(255,3,244,1)');
	this.init();
}

VFG.ClassificationPrimitive.prototype.init=function(){
	var _this=this;
	_this.primitive=new Cesium.ClassificationPrimitive({
		  geometryInstances: new Cesium.GeometryInstance({
		      geometry: Cesium.BoxGeometry.fromDimensions({
		            vertexFormat : Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,  
			        dimensions: new Cesium.Cartesian3(((_this.dimensions&& _this.dimensions.x) || 5.0),((_this.dimensions&& _this.dimensions.y) || 5.0),((_this.dimensions&& _this.dimensions.z) || 5.0)),
		      }),
		      modelMatrix:_this.getModelMatrix(),
		      attributes: {
		        color:Cesium.ColorGeometryInstanceAttribute.fromColor((_this.isView && _this.isView=='1')?_this.normalColor:_this.normalColor.withAlpha(0.0)),
		        show: new Cesium.ShowGeometryInstanceAttribute(true),
		      },
		      id:_this.id,
	    }),
	 })
}

/**
 * 计算矩阵
 */
VFG.ClassificationPrimitive.prototype.getModelMatrix=function(){
	var position = Cesium.Cartesian3.fromDegrees(this.position.x*1,this.position.y*1,this.position.z*1);
    var heading = Cesium.Math.toRadians(((this.rotation&& this.rotation.x) || 0.0));
    var pitch = Cesium.Math.toRadians(((this.rotation&& this.rotation.y) || 0.0));
    var roll = Cesium.Math.toRadians(((this.rotation&& this.rotation.z) || 0.0));
	var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(position);
	var hprRotation = Cesium.Matrix3.fromHeadingPitchRoll(new Cesium.HeadingPitchRoll(heading, pitch, roll));
	var hpr = Cesium.Matrix4.fromRotationTranslation(hprRotation,new Cesium.Cartesian3(0.0, 0.0, 0.0));
	Cesium.Matrix4.multiply(modelMatrix, hpr, modelMatrix);
	return modelMatrix;
}
VFG.ClassificationPrimitive.prototype.setNormalColor=function(color){
	if(this.primitive){
	    var attributes = this.primitive.getGeometryInstanceAttributes(this.id);
	    if(attributes){
	    	this.normalColor=Cesium.Color.fromCssColorString(color)
	    	if(this.isView=='1'){
	    		attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(this.normalColor)
	    	}else{
	    		attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(this.normalColor.withAlpha(0.0))
	    	}
	    }
	}
}

VFG.ClassificationPrimitive.prototype.setHoverColor=function(color){
	this.hoverColor=Cesium.Color.fromCssColorString(color)
}

/**
 * 显示
 */
VFG.ClassificationPrimitive.prototype.setDisplay=function(isView){
	if(this.primitive){
		this.isView=isView;
	    var attributes = this.primitive.getGeometryInstanceAttributes(this.id);
	    if(attributes){
			if('1'==isView){
		    	attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(this.normalColor); 
			}else{
				attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(this.normalColor.withAlpha(0.0)); 
			}
	    }
	}
}

/**
 * 旋转
 */
VFG.ClassificationPrimitive.prototype.rotateFeature=function(rotation){
	this.rotation=rotation;
	if(this.primitive){
		this.primitive._primitive.modelMatrix=this.getModelMatrix();
		
	}
}

/**
 * 移动
 */
VFG.ClassificationPrimitive.prototype.translateFeature=function(position){
	this.position=position;
	if(this.primitive){
		this.primitive._primitive.modelMatrix=this.getModelMatrix();
	}
}

VFG.ClassificationPrimitive.prototype.setDimensions=function(dimensions){
	var _this=this;
	_this.dimensions=dimensions;
	_this.primitive=new Cesium.ClassificationPrimitive({
		  geometryInstances: new Cesium.GeometryInstance({
		      geometry: Cesium.BoxGeometry.fromDimensions({
		            vertexFormat : Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,  
			        dimensions: new Cesium.Cartesian3(((_this.dimensions&& _this.dimensions.x) || 5.0),((_this.dimensions&& _this.dimensions.y) || 5.0),((_this.dimensions&& _this.dimensions.z) || 5.0)),
		      }),
		      modelMatrix:_this.getModelMatrix(),
		      attributes: {
		        color:Cesium.ColorGeometryInstanceAttribute.fromColor(_this.normalColor),
		        show: new Cesium.ShowGeometryInstanceAttribute(true),
		      },
		      id:_this.id,
	    }),
	 })
	return _this.primitive;
}

VFG.ClassificationPrimitive.prototype.enter=function(){
	if(this.primitive){
	    var attributes = this.primitive.getGeometryInstanceAttributes(this.id);
	    if(attributes){
	    	attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(this.hoverColor)
	    }
	}
}

VFG.ClassificationPrimitive.prototype.leave=function(){
	if(this.primitive){
	    var attributes = this.primitive.getGeometryInstanceAttributes(this.id);
	    if(attributes){
	    	if(this.isView=='1'){
	    		attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(this.normalColor)
	    	}else{
	    		attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(this.normalColor.withAlpha(0.0))
	    	}
	    }
	}
}
;
///<jscompress sourcefile="VFGHeatmap.js" />
/*
 *  CesiumHeatmap.js v0.1 | Cesium Heatmap Library
 *  
 *  Works with heatmap.js v2.0.0: http://www.patrick-wied.at/static/heatmapjs/
 */
(function (window) {
	'use strict';

	function define_CesiumHeatmap() {
		var CesiumHeatmap = {
			defaults: {
				useEntitiesIfAvailable: true, //whether to use entities if a Viewer is supplied or always use an ImageryProvider
				minCanvasSize: 700,           // minimum size (in pixels) for the heatmap canvas
				maxCanvasSize: 2000,          // maximum size (in pixels) for the heatmap canvas
				radiusFactor: 60,             // data point size factor used if no radius is given (the greater of height and width divided by this number yields the used radius)
				spacingFactor: 1.5,           // extra space around the borders (point radius multiplied by this number yields the spacing)
				maxOpacity: 0.8,              // the maximum opacity used if not given in the heatmap options object
				minOpacity: 0.1,              // the minimum opacity used if not given in the heatmap options object
				blur: 0.85,                   // the blur used if not given in the heatmap options object
				gradient: {                   // the gradient used if not given in the heatmap options object
					'.3': 'blue',
					'.65': 'yellow',
					'.8': 'orange',
					'.95': 'red'
				},
			}
		};

		/*  Create a CesiumHeatmap instance
		 *
		 *  cesium:  the CesiumWidget or Viewer instance
		 *  bb:      the WGS84 bounding box like {north, east, south, west}
		 *  options: a heatmap.js options object (see http://www.patrick-wied.at/static/heatmapjs/docs.html#h337-create)
		 */
		CesiumHeatmap.create = function (cesium, bb, options) {
			var instance = new CHInstance(cesium, bb, options);
			return instance;
		};

		CesiumHeatmap._getContainer = function (width, height, id) {
			var c = document.createElement("div");
			if (id) {
				c.setAttribute("id", id);
			}
			c.setAttribute("style", "width: " + width + "px; height: " + height + "px; margin: 0px; display: none;");
			document.body.appendChild(c);
			return c;
		};

		CesiumHeatmap._getImageryProvider = function (instance) {
			//var n = (new Date()).getTime();
			var d = instance._heatmap.getDataURL();
			//console.log("Create data URL: " + ((new Date()).getTime() - n));

			//var n = (new Date()).getTime();
			var imgprov = new Cesium.SingleTileImageryProvider({
				url: d,
				rectangle: instance._rectangle
			});
			//console.log("Create imageryprovider: " + ((new Date()).getTime() - n));

			imgprov._tilingScheme = new Cesium.WebMercatorTilingScheme({
				rectangleSouthwestInMeters: new Cesium.Cartesian2(instance._mbounds.west, instance._mbounds.south),
				rectangleNortheastInMeters: new Cesium.Cartesian2(instance._mbounds.east, instance._mbounds.north)
			});

			return imgprov;
		};

		CesiumHeatmap._getID = function (len) {
			var text = "";
			var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

			for (var i = 0; i < ((len) ? len : 8); i++)
				text += possible.charAt(Math.floor(Math.random() * possible.length));

			return text;
		};

		var WMP = new Cesium.WebMercatorProjection();

		/*  Convert a WGS84 location into a mercator location
		 *
		 *  p: the WGS84 location like {x: lon, y: lat}
		 */
		CesiumHeatmap.wgs84ToMercator = function (p) {
			var mp = WMP.project(Cesium.Cartographic.fromDegrees(p.x, p.y));
			return {
				x: mp.x,
				y: mp.y
			};
		};

		/*  Convert a WGS84 bounding box into a mercator bounding box
		 *
		 *  bb: the WGS84 bounding box like {north, east, south, west}
		 */
		CesiumHeatmap.wgs84ToMercatorBB = function (bb) {
			var sw = WMP.project(Cesium.Cartographic.fromDegrees(bb.west, bb.south));
			var ne = WMP.project(Cesium.Cartographic.fromDegrees(bb.east, bb.north));
			return {
				north: ne.y,
				east: ne.x,
				south: sw.y,
				west: sw.x
			};
		};

		/*  Convert a mercator location into a WGS84 location
		 *
		 *  p: the mercator lcation like {x, y}
		 */
		CesiumHeatmap.mercatorToWgs84 = function (p) {
			var wp = WMP.unproject(new Cesium.Cartesian3(p.x, p.y));
			return {
				x: wp.longitude,
				y: wp.latitude
			};
		};

		/*  Convert a mercator bounding box into a WGS84 bounding box
		 *
		 *  bb: the mercator bounding box like {north, east, south, west}
		 */
		CesiumHeatmap.mercatorToWgs84BB = function (bb) {
			var sw = WMP.unproject(new Cesium.Cartesian3(bb.west, bb.south));
			var ne = WMP.unproject(new Cesium.Cartesian3(bb.east, bb.north));
			return {
				north: this.rad2deg(ne.latitude),
				east: this.rad2deg(ne.longitude),
				south: this.rad2deg(sw.latitude),
				west: this.rad2deg(sw.longitude)
			};
		};

		/*  Convert degrees into radians
		 *
		 *  d: the degrees to be converted to radians
		 */
		CesiumHeatmap.deg2rad = function (d) {
			var r = d * (Math.PI / 180.0);
			return r;
		};

		/*  Convert radians into degrees
		 *
		 *  r: the radians to be converted to degrees
		 */
		CesiumHeatmap.rad2deg = function (r) {
			var d = r / (Math.PI / 180.0);
			return d;
		};

		return CesiumHeatmap;
	}

	if (typeof(CesiumHeatmap) === 'undefined') {
		window.CesiumHeatmap = define_CesiumHeatmap();
	} else {
		console.log("CesiumHeatmap already defined.");
	}
})(window);

/*  Initiate a CesiumHeatmap instance
 *
 *  c:  CesiumWidget instance
 *  bb: a WGS84 bounding box like {north, east, south, west}
 *  o:  a heatmap.js options object (see http://www.patrick-wied.at/static/heatmapjs/docs.html#h337-create)
 */
function CHInstance(c, bb, o) {
	if (!bb) {
		return null;
	}
	if (!o) {
		o = {};
	}

	this._cesium = c;
	this._options = o;
	this._id = CesiumHeatmap._getID();

	this._options.gradient = ((this._options.gradient) ? this._options.gradient : CesiumHeatmap.defaults.gradient);
	this._options.maxOpacity = ((this._options.maxOpacity) ? this._options.maxOpacity : CesiumHeatmap.defaults.maxOpacity);
	this._options.minOpacity = ((this._options.minOpacity) ? this._options.minOpacity : CesiumHeatmap.defaults.minOpacity);
	this._options.blur = ((this._options.blur) ? this._options.blur : CesiumHeatmap.defaults.blur);

	this._mbounds = CesiumHeatmap.wgs84ToMercatorBB(bb);
	this._setWidthAndHeight(this._mbounds);

	this._options.radius = Math.round((this._options.radius) ? this._options.radius : ((this.width > this.height) ? this.width / CesiumHeatmap.defaults.radiusFactor : this.height / CesiumHeatmap.defaults.radiusFactor));

	this._spacing = this._options.radius * CesiumHeatmap.defaults.spacingFactor;
	this._xoffset = this._mbounds.west;
	this._yoffset = this._mbounds.south;

	this.width = Math.round(this.width + this._spacing * 2);
	this.height = Math.round(this.height + this._spacing * 2);

	this._mbounds.west -= this._spacing * this._factor;
	this._mbounds.east += this._spacing * this._factor;
	this._mbounds.south -= this._spacing * this._factor;
	this._mbounds.north += this._spacing * this._factor;

	this.bounds = CesiumHeatmap.mercatorToWgs84BB(this._mbounds);

	this._rectangle = Cesium.Rectangle.fromDegrees(this.bounds.west, this.bounds.south, this.bounds.east, this.bounds.north);
	this._container = CesiumHeatmap._getContainer(this.width, this.height, this._id);
	this._options.container = this._container;
	this._heatmap = h337.create(this._options);
	this._container.children[0].setAttribute("id", this._id + "-hm");
}

/*  Convert a WGS84 location to the corresponding heatmap location
 *
 *  p: a WGS84 location like {x:lon, y:lat}
 */
CHInstance.prototype.wgs84PointToHeatmapPoint = function (p) {
	return this.mercatorPointToHeatmapPoint(CesiumHeatmap.wgs84ToMercator(p));
};

/*  Convert a mercator location to the corresponding heatmap location
 *
 *  p: a WGS84 location like {x: lon, y:lat}
 */
CHInstance.prototype.mercatorPointToHeatmapPoint = function (p) {
	var pn = {};

	pn.x = Math.round((p.x - this._xoffset) / this._factor + this._spacing);
	pn.y = Math.round((p.y - this._yoffset) / this._factor + this._spacing);
	pn.y = this.height - pn.y;

	return pn;
};

CHInstance.prototype._setWidthAndHeight = function (mbb) {
	this.width = ((mbb.east > 0 && mbb.west < 0) ? mbb.east + Math.abs(mbb.west) : Math.abs(mbb.east - mbb.west));
	this.height = ((mbb.north > 0 && mbb.south < 0) ? mbb.north + Math.abs(mbb.south) : Math.abs(mbb.north - mbb.south));
	this._factor = 1;

	if (this.width > this.height && this.width > CesiumHeatmap.defaults.maxCanvasSize) {
		this._factor = this.width / CesiumHeatmap.defaults.maxCanvasSize;

		if (this.height / this._factor < CesiumHeatmap.defaults.minCanvasSize) {
			this._factor = this.height / CesiumHeatmap.defaults.minCanvasSize;
		}
	} else if (this.height > this.width && this.height > CesiumHeatmap.defaults.maxCanvasSize) {
		this._factor = this.height / CesiumHeatmap.defaults.maxCanvasSize;

		if (this.width / this._factor < CesiumHeatmap.defaults.minCanvasSize) {
			this._factor = this.width / CesiumHeatmap.defaults.minCanvasSize;
		}
	} else if (this.width < this.height && this.width < CesiumHeatmap.defaults.minCanvasSize) {
		this._factor = this.width / CesiumHeatmap.defaults.minCanvasSize;

		if (this.height / this._factor > CesiumHeatmap.defaults.maxCanvasSize) {
			this._factor = this.height / CesiumHeatmap.defaults.maxCanvasSize;
		}
	} else if (this.height < this.width && this.height < CesiumHeatmap.defaults.minCanvasSize) {
		this._factor = this.height / CesiumHeatmap.defaults.minCanvasSize;

		if (this.width / this._factor > CesiumHeatmap.defaults.maxCanvasSize) {
			this._factor = this.width / CesiumHeatmap.defaults.maxCanvasSize;
		}
	}

	this.width = this.width / this._factor;
	this.height = this.height / this._factor;
};

/*  Set an array of heatmap locations
 *
 *  min:  the minimum allowed value for the data values
 *  max:  the maximum allowed value for the data values
 *  data: an array of data points in heatmap coordinates and values like {x, y, value}
 */
CHInstance.prototype.setData = function (min, max, data) {
	if (data && data.length > 0 && min !== null && min !== false && max !== null && max !== false) {
		this._heatmap.setData({
			min: min,
			max: max,
			data: data
		});

		this.updateLayer();
		return true;
	}

	return false;
};

/*  Set an array of WGS84 locations
 *
 *  min:  the minimum allowed value for the data values
 *  max:  the maximum allowed value for the data values
 *  data: an array of data points in WGS84 coordinates and values like { x:lon, y:lat, value }
 */
CHInstance.prototype.setWGS84Data = function (min, max, data) {
	if (data && data.length > 0 && min !== null && min !== false && max !== null && max !== false) {
		var convdata = [];

		for (var i = 0; i < data.length; i++) {
			var gp = data[i];

			var hp = this.wgs84PointToHeatmapPoint(gp);
			if (gp.value || gp.value === 0) {
				hp.value = gp.value;
			}

			convdata.push(hp);
		}

		return this.setData(min, max, convdata);
	}

	return false;
};

/*  Set whether or not the heatmap is shown on the map
 *
 *  s: true means the heatmap is shown, false means the heatmap is hidden
 */
CHInstance.prototype.show = function (s) {
	if (this._layer) {
		this._layer.show = s;
	}
};

/*  Update/(re)draw the heatmap
 */
CHInstance.prototype.updateLayer = function () {

	// only works with a Viewer instance since the cesiumWidget
	// instance doesn't contain an entities property
	if (CesiumHeatmap.defaults.useEntitiesIfAvailable && this._cesium.entities) {
		if (this._layer) {
			this._cesium.entities.remove(this._layer);
		}

		// Work around issue with material rendering in Cesium
		// provided by https://github.com/criis
		material = new Cesium.ImageMaterialProperty({
			image: this._heatmap._renderer.canvas,
		});
		if (Cesium.VERSION >= "1.21") {
			material.transparent = true;
		} else if (Cesium.VERSION >= "1.16") {
			material.alpha = 0.99;
		}

		this._layer = this._cesium.entities.add({
			show: true,
			rectangle: {
				coordinates: this._rectangle,
				material: material
			}
		});
	} else {
		if (this._layer) {
			this._cesium.scene.imageryLayers.remove(this._layer);
		}

		this._layer = this._cesium.scene.imageryLayers.addImageryProvider(CesiumHeatmap._getImageryProvider(this));
	}
};

/**
 * 移除
 */
CHInstance.prototype.removeLayer = function () {
	if (CesiumHeatmap.defaults.useEntitiesIfAvailable && this._cesium.entities) {
		if (this._layer) {
			this._cesium.entities.remove(this._layer);
		}
	} else {
		if (this._layer) {
			this._cesium.scene.imageryLayers.remove(this._layer);
		}

	}
};



/*  DON'T TOUCH:
 *
 *  heatmap.js v2.0.0 | JavaScript Heatmap Library: http://www.patrick-wied.at/static/heatmapjs/
 *
 *  Copyright 2008-2014 Patrick Wied <heatmapjs@patrick-wied.at> - All rights reserved.
 *  Dual licensed under MIT and Beerware license
 *
 *  :: 2014-10-31 21:16
 */
(function (a, b, c) {
	if (typeof module !== "undefined" && module.exports) {
		module.exports = c()
	} else if (typeof define === "function" && define.amd) {
		define(c)
	} else {
		b[a] = c()
	}
})("h337", this, function () {
	var a = {
		defaultRadius: 40,
		defaultRenderer: "canvas2d",
		defaultGradient: {.25: "rgb(0,0,255)", .55: "rgb(0,255,0)", .85: "yellow", 1: "rgb(255,0,0)"},
		defaultMaxOpacity: 1,
		defaultMinOpacity: 0,
		defaultBlur: .85,
		defaultXField: "x",
		defaultYField: "y",
		defaultValueField: "value",
		plugins: {}
	};
	var b = function h() {
		var b = function d(a) {
			this._coordinator = {};
			this._data = [];
			this._radi = [];
			this._min = 0;
			this._max = 1;
			this._xField = a["xField"] || a.defaultXField;
			this._yField = a["yField"] || a.defaultYField;
			this._valueField = a["valueField"] || a.defaultValueField;
			if (a["radius"]) {
				this._cfgRadius = a["radius"]
			}
		};
		var c = a.defaultRadius;
		b.prototype = {
			_organiseData: function (a, b) {
				var d = a[this._xField];
				var e = a[this._yField];
				var f = this._radi;
				var g = this._data;
				var h = this._max;
				var i = this._min;
				var j = a[this._valueField] || 1;
				var k = a.radius || this._cfgRadius || c;
				if (!g[d]) {
					g[d] = [];
					f[d] = []
				}
				if (!g[d][e]) {
					g[d][e] = j;
					f[d][e] = k
				} else {
					g[d][e] += j
				}
				if (g[d][e] > h) {
					if (!b) {
						this._max = g[d][e]
					} else {
						this.setDataMax(g[d][e])
					}
					return false
				} else {
					return {x: d, y: e, value: j, radius: k, min: i, max: h}
				}
			}, _unOrganizeData: function () {
				var a = [];
				var b = this._data;
				var c = this._radi;
				for (var d in b) {
					for (var e in b[d]) {
						a.push({x: d, y: e, radius: c[d][e], value: b[d][e]})
					}
				}
				return {min: this._min, max: this._max, data: a}
			}, _onExtremaChange: function () {
				this._coordinator.emit("extremachange", {min: this._min, max: this._max})
			}, addData: function () {
				if (arguments[0].length > 0) {
					var a = arguments[0];
					var b = a.length;
					while (b--) {
						this.addData.call(this, a[b])
					}
				} else {
					var c = this._organiseData(arguments[0], true);
					if (c) {
						this._coordinator.emit("renderpartial", {min: this._min, max: this._max, data: [c]})
					}
				}
				return this
			}, setData: function (a) {
				var b = a.data;
				var c = b.length;
				this._data = [];
				this._radi = [];
				for (var d = 0; d < c; d++) {
					this._organiseData(b[d], false)
				}
				this._max = a.max;
				this._min = a.min || 0;
				this._onExtremaChange();
				this._coordinator.emit("renderall", this._getInternalData());
				return this
			}, removeData: function () {
			}, setDataMax: function (a) {
				this._max = a;
				this._onExtremaChange();
				this._coordinator.emit("renderall", this._getInternalData());
				return this
			}, setDataMin: function (a) {
				this._min = a;
				this._onExtremaChange();
				this._coordinator.emit("renderall", this._getInternalData());
				return this
			}, setCoordinator: function (a) {
				this._coordinator = a
			}, _getInternalData: function () {
				return {max: this._max, min: this._min, data: this._data, radi: this._radi}
			}, getData: function () {
				return this._unOrganizeData()
			}
		};
		return b
	}();
	var c = function i() {
		var a = function (a) {
			var b = a.gradient || a.defaultGradient;
			var c = document.createElement("canvas");
			var d = c.getContext("2d");
			c.width = 256;
			c.height = 1;
			var e = d.createLinearGradient(0, 0, 256, 1);
			for (var f in b) {
				e.addColorStop(f, b[f])
			}
			d.fillStyle = e;
			d.fillRect(0, 0, 256, 1);
			return d.getImageData(0, 0, 256, 1).data
		};
		var b = function (a, b) {
			var c = document.createElement("canvas");
			var d = c.getContext("2d");
			var e = a;
			var f = a;
			c.width = c.height = a * 2;
			if (b == 1) {
				d.beginPath();
				d.arc(e, f, a, 0, 2 * Math.PI, false);
				d.fillStyle = "rgba(0,0,0,1)";
				d.fill()
			} else {
				var g = d.createRadialGradient(e, f, a * b, e, f, a);
				g.addColorStop(0, "rgba(0,0,0,1)");
				g.addColorStop(1, "rgba(0,0,0,0)");
				d.fillStyle = g;
				d.fillRect(0, 0, 2 * a, 2 * a)
			}
			return c
		};
		var c = function (a) {
			var b = [];
			var c = a.min;
			var d = a.max;
			var e = a.radi;
			var a = a.data;
			var f = Object.keys(a);
			var g = f.length;
			while (g--) {
				var h = f[g];
				var i = Object.keys(a[h]);
				var j = i.length;
				while (j--) {
					var k = i[j];
					var l = a[h][k];
					var m = e[h][k];
					b.push({x: h, y: k, value: l, radius: m})
				}
			}
			return {min: c, max: d, data: b}
		};

		function d(b) {
			var c = b.container;
			var d = this.shadowCanvas = document.createElement("canvas");
			var e = this.canvas = b.canvas || document.createElement("canvas");
			var f = this._renderBoundaries = [1e4, 1e4, 0, 0];
			var g = getComputedStyle(b.container) || {};
			e.className = "heatmap-canvas";
			this._width = e.width = d.width = +g.width.replace(/px/, "");
			this._height = e.height = d.height = +g.height.replace(/px/, "");
			this.shadowCtx = d.getContext("2d");
			this.ctx = e.getContext("2d");
			e.style.cssText = d.style.cssText = "position:absolute;left:0;top:0;";
			c.style.position = "relative";
			c.appendChild(e);
			this._palette = a(b);
			this._templates = {};
			this._setStyles(b)
		}

		d.prototype = {
			renderPartial: function (a) {
				this._drawAlpha(a);
				this._colorize()
			}, renderAll: function (a) {
				this._clear();
				this._drawAlpha(c(a));
				this._colorize()
			}, _updateGradient: function (b) {
				this._palette = a(b)
			}, updateConfig: function (a) {
				if (a["gradient"]) {
					this._updateGradient(a)
				}
				this._setStyles(a)
			}, setDimensions: function (a, b) {
				this._width = a;
				this._height = b;
				this.canvas.width = this.shadowCanvas.width = a;
				this.canvas.height = this.shadowCanvas.height = b
			}, _clear: function () {
				this.shadowCtx.clearRect(0, 0, this._width, this._height);
				this.ctx.clearRect(0, 0, this._width, this._height)
			}, _setStyles: function (a) {
				this._blur = a.blur == 0 ? 0 : a.blur || a.defaultBlur;
				if (a.backgroundColor) {
					this.canvas.style.backgroundColor = a.backgroundColor
				}
				this._opacity = (a.opacity || 0) * 255;
				this._maxOpacity = (a.maxOpacity || a.defaultMaxOpacity) * 255;
				this._minOpacity = (a.minOpacity || a.defaultMinOpacity) * 255;
				this._useGradientOpacity = !!a.useGradientOpacity
			}, _drawAlpha: function (a) {
				var c = this._min = a.min;
				var d = this._max = a.max;
				var a = a.data || [];
				var e = a.length;
				var f = 1 - this._blur;
				while (e--) {
					var g = a[e];
					var h = g.x;
					var i = g.y;
					var j = g.radius;
					var k = Math.min(g.value, d);
					var l = h - j;
					var m = i - j;
					var n = this.shadowCtx;
					var o;
					if (!this._templates[j]) {
						this._templates[j] = o = b(j, f)
					} else {
						o = this._templates[j]
					}
					n.globalAlpha = (k - c) / (d - c);
					n.drawImage(o, l, m);
					if (l < this._renderBoundaries[0]) {
						this._renderBoundaries[0] = l
					}
					if (m < this._renderBoundaries[1]) {
						this._renderBoundaries[1] = m
					}
					if (l + 2 * j > this._renderBoundaries[2]) {
						this._renderBoundaries[2] = l + 2 * j
					}
					if (m + 2 * j > this._renderBoundaries[3]) {
						this._renderBoundaries[3] = m + 2 * j
					}
				}
			}, _colorize: function () {
				var a = this._renderBoundaries[0];
				var b = this._renderBoundaries[1];
				var c = this._renderBoundaries[2] - a;
				var d = this._renderBoundaries[3] - b;
				var e = this._width;
				var f = this._height;
				var g = this._opacity;
				var h = this._maxOpacity;
				var i = this._minOpacity;
				var j = this._useGradientOpacity;
				if (a < 0) {
					a = 0
				}
				if (b < 0) {
					b = 0
				}
				if (a + c > e) {
					c = e - a
				}
				if (b + d > f) {
					d = f - b
				}
				var k = this.shadowCtx.getImageData(a, b, c, d);
				var l = k.data;
				var m = l.length;
				var n = this._palette;
				for (var o = 3; o < m; o += 4) {
					var p = l[o];
					var q = p * 4;
					if (!q) {
						continue
					}
					var r;
					if (g > 0) {
						r = g
					} else {
						if (p < h) {
							if (p < i) {
								r = i
							} else {
								r = p
							}
						} else {
							r = h
						}
					}
					l[o - 3] = n[q];
					l[o - 2] = n[q + 1];
					l[o - 1] = n[q + 2];
					l[o] = j ? n[q + 3] : r
				}
				k.data = l;
				this.ctx.putImageData(k, a, b);
				this._renderBoundaries = [1e3, 1e3, 0, 0]
			}, getValueAt: function (a) {
				var b;
				var c = this.shadowCtx;
				var d = c.getImageData(a.x, a.y, 1, 1);
				var e = d.data[3];
				var f = this._max;
				var g = this._min;
				b = Math.abs(f - g) * (e / 255) >> 0;
				return b
			}, getDataURL: function () {
				return this.canvas.toDataURL()
			}
		};
		return d
	}();
	var d = function j() {
		var b = false;
		if (a["defaultRenderer"] === "canvas2d") {
			b = c
		}
		return b
	}();
	var e = {
		merge: function () {
			var a = {};
			var b = arguments.length;
			for (var c = 0; c < b; c++) {
				var d = arguments[c];
				for (var e in d) {
					a[e] = d[e]
				}
			}
			return a
		}
	};
	var f = function k() {
		var c = function h() {
			function a() {
				this.cStore = {}
			}

			a.prototype = {
				on: function (a, b, c) {
					var d = this.cStore;
					if (!d[a]) {
						d[a] = []
					}
					d[a].push(function (a) {
						return b.call(c, a)
					})
				}, emit: function (a, b) {
					var c = this.cStore;
					if (c[a]) {
						var d = c[a].length;
						for (var e = 0; e < d; e++) {
							var f = c[a][e];
							f(b)
						}
					}
				}
			};
			return a
		}();
		var f = function (a) {
			var b = a._renderer;
			var c = a._coordinator;
			var d = a._store;
			c.on("renderpartial", b.renderPartial, b);
			c.on("renderall", b.renderAll, b);
			c.on("extremachange", function (b) {
				a._config.onExtremaChange && a._config.onExtremaChange({
					min: b.min,
					max: b.max,
					gradient: a._config["gradient"] || a._config["defaultGradient"]
				})
			});
			d.setCoordinator(c)
		};

		function g() {
			var g = this._config = e.merge(a, arguments[0] || {});
			this._coordinator = new c;
			if (g["plugin"]) {
				var h = g["plugin"];
				if (!a.plugins[h]) {
					throw new Error("Plugin '" + h + "' not found. Maybe it was not registered.")
				} else {
					var i = a.plugins[h];
					this._renderer = new i.renderer(g);
					this._store = new i.store(g)
				}
			} else {
				this._renderer = new d(g);
				this._store = new b(g)
			}
			f(this)
		}

		g.prototype = {
			addData: function () {
				this._store.addData.apply(this._store, arguments);
				return this
			}, removeData: function () {
				this._store.removeData && this._store.removeData.apply(this._store, arguments);
				return this
			}, setData: function () {
				this._store.setData.apply(this._store, arguments);
				return this
			}, setDataMax: function () {
				this._store.setDataMax.apply(this._store, arguments);
				return this
			}, setDataMin: function () {
				this._store.setDataMin.apply(this._store, arguments);
				return this
			}, configure: function (a) {
				this._config = e.merge(this._config, a);
				this._renderer.updateConfig(this._config);
				this._coordinator.emit("renderall", this._store._getInternalData());
				return this
			}, repaint: function () {
				this._coordinator.emit("renderall", this._store._getInternalData());
				return this
			}, getData: function () {
				return this._store.getData()
			}, getDataURL: function () {
				return this._renderer.getDataURL()
			}, getValueAt: function (a) {
				if (this._store.getValueAt) {
					return this._store.getValueAt(a)
				} else if (this._renderer.getValueAt) {
					return this._renderer.getValueAt(a)
				} else {
					return null
				}
			}
		};
		return g
	}();
	var g = {
		create: function (a) {
			return new f(a)
		}, register: function (b, c) {
			a.plugins[b] = c
		}
	};
	return g
});;
///<jscompress sourcefile="VFGRadarScan.js" />
/*new VFG.RadarScan(viewer,{
	x:103.38398032314626,
	y:23.368851347473854,
	color:'rgb(255,255,44)',
	radius:1000,
	interval:4000,
})*/

VFG.RadarScan=function(viewer,option){
	if(!viewer){
		return;
	}
	if(!option){
		return;
	}
	this.viewer=viewer;
	this.option=option;
	this.init();
}
VFG.RadarScan.prototype.init=function(){
	var _this=this;
	this.viewer.scene.globe.depthTestAgainstTerrain = true; 
    var cartographicCenter = new Cesium.Cartographic(Cesium.Math.toRadians(this.option.x*1), Cesium.Math.toRadians(this.option.y*1),0); //中心位子
    var radius=this.option.radius*1;
    var duration=this.option.interval*1;
    var scanColor=Cesium.Color.fromCssColorString(this.option.color);
    var ScanSegmentShader =
        "uniform sampler2D colorTexture;\n" +
        "uniform sampler2D depthTexture;\n" +
        "varying vec2 v_textureCoordinates;\n" +
        "uniform vec4 u_scanCenterEC;\n" +
        "uniform vec3 u_scanPlaneNormalEC;\n" +
        "uniform vec3 u_scanLineNormalEC;\n" +
        "uniform float u_radius;\n" +
        "uniform vec4 u_scanColor;\n" +
        "vec4 toEye(in vec2 uv, in float depth)\n" +
        " {\n" +
        " vec2 xy = vec2((uv.x * 2.0 - 1.0),(uv.y * 2.0 - 1.0));\n" +
        " vec4 posInCamera =czm_inverseProjection * vec4(xy, depth, 1.0);\n" +
        " posInCamera =posInCamera / posInCamera.w;\n" +
        " return posInCamera;\n" +
        " }\n" +
        "bool isPointOnLineRight(in vec3 ptOnLine, in vec3 lineNormal, in vec3 testPt)\n" +
        "{\n" +
        "vec3 v01 = testPt - ptOnLine;\n" +
        "normalize(v01);\n" +
        "vec3 temp = cross(v01, lineNormal);\n" +
        "float d = dot(temp, u_scanPlaneNormalEC);\n" +
        "return d > 0.5;\n" +
        "}\n" +
        "vec3 pointProjectOnPlane(in vec3 planeNormal, in vec3 planeOrigin, in vec3 point)\n" +
        "{\n" +
        "vec3 v01 = point -planeOrigin;\n" +
        "float d = dot(planeNormal, v01) ;\n" +
        "return (point - planeNormal * d);\n" +
        "}\n" +
        "float distancePointToLine(in vec3 ptOnLine, in vec3 lineNormal, in vec3 testPt)\n" +
        "{\n" +
        "vec3 tempPt = pointProjectOnPlane(lineNormal, ptOnLine, testPt);\n" +
        "return length(tempPt - ptOnLine);\n" +
        "}\n" +
        "float getDepth(in vec4 depth)\n" +
        "{\n" +
        "float z_window = czm_unpackDepth(depth);\n" +
        "z_window = czm_reverseLogDepth(z_window);\n" +
        "float n_range = czm_depthRange.near;\n" +
        "float f_range = czm_depthRange.far;\n" +
        "return (2.0 * z_window - n_range - f_range) / (f_range - n_range);\n" +
        "}\n" +
        "void main()\n" +
        "{\n" +
        "gl_FragColor = texture2D(colorTexture, v_textureCoordinates);\n" +
        "float depth = getDepth( texture2D(depthTexture, v_textureCoordinates));\n" +
        "vec4 viewPos = toEye(v_textureCoordinates, depth);\n" +
        "vec3 prjOnPlane = pointProjectOnPlane(u_scanPlaneNormalEC.xyz, u_scanCenterEC.xyz, viewPos.xyz);\n" +
        "float dis = length(prjOnPlane.xyz - u_scanCenterEC.xyz);\n" +
        "float twou_radius = u_radius * 2.0;\n" +
        "if(dis < u_radius)\n" +
        "{\n" +
        "float f0 = 1.0 -abs(u_radius - dis) / u_radius;\n" +
        "f0 = pow(f0, 64.0);\n" +
        "vec3 lineEndPt = vec3(u_scanCenterEC.xyz) + u_scanLineNormalEC * u_radius;\n" +
        "float f = 0.0;\n" +
        "if(isPointOnLineRight(u_scanCenterEC.xyz, u_scanLineNormalEC.xyz, prjOnPlane.xyz))\n" +
        "{\n" +
        "float dis1= length(prjOnPlane.xyz - lineEndPt);\n" +
        "f = abs(twou_radius -dis1) / twou_radius;\n" +
        "f = pow(f, 3.0);\n" +
        "}\n" +
        "gl_FragColor = mix(gl_FragColor, u_scanColor, f + f0);\n" +
        "}\n" +
        "}\n";

    var _Cartesian3Center = Cesium.Cartographic.toCartesian(cartographicCenter);
    var _Cartesian4Center = new Cesium.Cartesian4(_Cartesian3Center.x, _Cartesian3Center.y, _Cartesian3Center.z, 1);
    var _CartographicCenter1 = new Cesium.Cartographic(cartographicCenter.longitude, cartographicCenter.latitude, cartographicCenter.height + 500);
    var _Cartesian3Center1 = Cesium.Cartographic.toCartesian(_CartographicCenter1);
    var _Cartesian4Center1 = new Cesium.Cartesian4(_Cartesian3Center1.x, _Cartesian3Center1.y, _Cartesian3Center1.z, 1);
    var _CartographicCenter2 = new Cesium.Cartographic(cartographicCenter.longitude + Cesium.Math.toRadians(0.001), cartographicCenter.latitude, cartographicCenter.height);
    var _Cartesian3Center2 = Cesium.Cartographic.toCartesian(_CartographicCenter2);
    var _Cartesian4Center2 = new Cesium.Cartesian4(_Cartesian3Center2.x, _Cartesian3Center2.y, _Cartesian3Center2.z, 1);
    var _RotateQ = new Cesium.Quaternion();
    var _RotateM = new Cesium.Matrix3();
    var _time = (new Date()).getTime();
    var _scratchCartesian4Center = new Cesium.Cartesian4();
    var _scratchCartesian4Center1 = new Cesium.Cartesian4();
    var _scratchCartesian4Center2 = new Cesium.Cartesian4();
    var _scratchCartesian3Normal = new Cesium.Cartesian3();
    var _scratchCartesian3Normal1 = new Cesium.Cartesian3();
    _this.scanPostStage = new Cesium.PostProcessStage({
        fragmentShader: ScanSegmentShader,
        uniforms: {
            u_scanCenterEC: function () {
                return Cesium.Matrix4.multiplyByVector(viewer.camera._viewMatrix, _Cartesian4Center, _scratchCartesian4Center);
            },
            u_scanPlaneNormalEC: function () {
                var temp = Cesium.Matrix4.multiplyByVector(viewer.camera._viewMatrix, _Cartesian4Center, _scratchCartesian4Center);
                var temp1 = Cesium.Matrix4.multiplyByVector(viewer.camera._viewMatrix, _Cartesian4Center1, _scratchCartesian4Center1);
                _scratchCartesian3Normal.x = temp1.x - temp.x;
                _scratchCartesian3Normal.y = temp1.y - temp.y;
                _scratchCartesian3Normal.z = temp1.z - temp.z;
                Cesium.Cartesian3.normalize(_scratchCartesian3Normal, _scratchCartesian3Normal);
                return _scratchCartesian3Normal;

            },
            u_radius: radius,
            u_scanLineNormalEC: function () {
                var temp = Cesium.Matrix4.multiplyByVector(viewer.camera._viewMatrix, _Cartesian4Center, _scratchCartesian4Center);
                var temp1 = Cesium.Matrix4.multiplyByVector(viewer.camera._viewMatrix, _Cartesian4Center1, _scratchCartesian4Center1);
                var temp2 = Cesium.Matrix4.multiplyByVector(viewer.camera._viewMatrix, _Cartesian4Center2, _scratchCartesian4Center2);
                _scratchCartesian3Normal.x = temp1.x - temp.x;
                _scratchCartesian3Normal.y = temp1.y - temp.y;
                _scratchCartesian3Normal.z = temp1.z - temp.z;
                Cesium.Cartesian3.normalize(_scratchCartesian3Normal, _scratchCartesian3Normal);
                _scratchCartesian3Normal1.x = temp2.x - temp.x;
                _scratchCartesian3Normal1.y = temp2.y - temp.y;
                _scratchCartesian3Normal1.z = temp2.z - temp.z;
                var tempTime = (((new Date()).getTime() - _time) % duration) / duration;
                Cesium.Quaternion.fromAxisAngle(_scratchCartesian3Normal, tempTime * Cesium.Math.PI * 2, _RotateQ);
                Cesium.Matrix3.fromQuaternion(_RotateQ, _RotateM);
                Cesium.Matrix3.multiplyByVector(_RotateM, _scratchCartesian3Normal1, _scratchCartesian3Normal1);
                Cesium.Cartesian3.normalize(_scratchCartesian3Normal1, _scratchCartesian3Normal1);
                return _scratchCartesian3Normal1;
            },
            u_scanColor: scanColor
        }
    });
    _this.viewer.scene.postProcessStages.add(_this.scanPostStage);
}
VFG.RadarScan.prototype.destroy = function() {
	if(this.scanPostStage){
        this.viewer.scene.postProcessStages.remove(this.scanPostStage);
	}
    delete this.option,
    delete this.scanPostStage,
    delete this.viewer
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="VFGRoam.js" />
VFG.Roam=function(viewer,option){
	this.viewer=viewer;
	this.option=option;
	this.paths=this.getCartesian3Array(option.points);
	this.times=(option.times?option.times*1:60);
	this.followedX=(option.followedX?option.followedX*1:50);//距离运动点的距离（后方） 
	this.followedZ=(option.followedZ?option.followedZ*1:10);//距离运动点的高度（上方）
	this.speed=(option.speed?option.speed*1:10);;
	this.isTracked=(option.isTracked&&option.isTracked=='1'?true:false);
	this.height=option.height||null;//高度
	this.clockRange=this.getClockRange(option.clockRange);//高度
	this.init();
}

VFG.Roam.prototype.init = function() {
	var _self = this;
	var property = _self.getProperty(this.paths, this.times);
	_self.entity = _self.viewer.entities.add({
        availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
            start: _self.start,
            stop: _self.stop
        })]),
        position: property,
        orientation: new Cesium.VelocityOrientationProperty(property),
        point:{
			color: new Cesium.Color.fromCssColorString("#FFFF00").withAlpha(0.2),
			pixelSize: 1
        },
    });
    this.entity.position.setInterpolationOptions({ // 点插值
        interpolationDegree: 5,
        interpolationAlgorithm: Cesium.LinearApproximation
    });
    
    if(_self.isTracked){
    	 _self.viewer.trackedEntity = _self.entity;
    }
   
	var scratch = new Cesium.Matrix4();
	_self.renderListener = function(e) {
		var time = _self.viewer.clock.currentTime.secondsOfDay - _self.viewer.clock.startTime.secondsOfDay;
		if (_self.entity) {
			_self.getModelMatrix(_self.entity, _self.viewer.clock.currentTime, scratch);
			var transformX = _self.followedX || 50; //距离运动点的距离（后方） 
			var transformZ = _self.followedZ || 10; //距离运动点的高度（上方）
			_self.viewer.scene.camera.lookAtTransform(scratch, new Cesium.Cartesian3(-transformX, 0, transformZ));
		}
	}
	_self.viewer.scene.preRender.addEventListener(_self.renderListener);
	this.viewer.clock.shouldAnimate = true;
};

//计算漫游
VFG.Roam.prototype.getProperty = function(paths, times) {
    var property = new Cesium.SampledPositionProperty();
    var lineLength = paths.length;
    var tempTime = times - times % lineLength;
    var increment = tempTime / lineLength;
    var start = Cesium.JulianDate.now()
    this.start = start;
    var stop = Cesium.JulianDate.addSeconds(start, tempTime, new Cesium.JulianDate());
    this.stop = stop;
    this.viewer.clock.startTime = start.clone();
    this.viewer.clock.stopTime = stop.clone();
    this.viewer.clock.currentTime = start.clone();
    this.viewer.clock.clockRange =this.clockRange; // Loop at the end
    this.viewer.clock.multiplier = this.speed;
  //  this.viewer.clock.onStop.addEventListener(this.options.complete);
    for ( i = 0; i < lineLength; i++) {
        var time = Cesium.JulianDate.addSeconds(start, i * increment, new Cesium.JulianDate());
        property.addSample(time,paths[i]);
    }
    return property;
}

/**
 * 计算多个点位总长度
 */
VFG.Roam.prototype.getTotalLength = function(points) {
	 var _self = this;
	 var linePoint=[];
	 for(var point of points){
		 var item=[];
		 item.push(point.x*1);
		 item.push(point.y*1);
		 linePoint.push(item);
	 }
	 if(linePoint.length>0){
		 var line = turf.lineString(linePoint);
	     return turf.length(line, {units: 'kilometers'});
	 }
	 return 0;
};

//视角变换
VFG.Roam.prototype.getModelMatrix=function(entity, time, result) {
	var matrix3Scratch = new Cesium.Matrix3();
	var position = Cesium.Property.getValueOrUndefined(entity.position, time, new Cesium.Cartesian3());
	if (!Cesium.defined(position)) {
		return undefined;
	}
	var orientation = Cesium.Property.getValueOrUndefined(entity.orientation, time, new Cesium.Quaternion());
	if (!Cesium.defined(orientation)) {
		result = Cesium.Transforms.eastNorthUpToFixedFrame(position, undefined, result);
	} else {
		result = Cesium.Matrix4.fromRotationTranslation(Cesium.Matrix3.fromQuaternion(orientation, matrix3Scratch),
			position, result);
	}
	return result;
}

VFG.Roam.prototype.getCartesian3Array=function(list) {
	var arr=[];
	for(var point of list){
		if(this.height){
			arr.push(Cesium.Cartesian3.fromDegrees(point.x*1,point.y*1,this.height));
		}else{
			arr.push(Cesium.Cartesian3.fromDegrees(point.x*1,point.y*1,point.z*1));
		}
	}
	return arr;
}

VFG.Roam.prototype.getClockRange=function(clockRange) {
	if(clockRange=='CLAMPED'){
		return Cesium.ClockRange.CLAMPED;
	}
	else if(clockRange=='LOOP_STOP'){
		return Cesium.ClockRange.LOOP_STOP;
	}
	else if(clockRange=='UNBOUNDED'){
		return Cesium.ClockRange.UNBOUNDED;
	}else{
		return Cesium.ClockRange.LOOP_STOP;
	}
}

/**
 *漫游的暂停和继续
 * @param {*} state bool类型 false为暂停，ture为继续
 * @memberof Roaming
 */
VFG.Roam.prototype.PauseOrContinue = function(state) {
    this.viewer.clock.shouldAnimate = state;
}
/**
 *改变飞行的速度
 * @param {*} value  整数类型
 * @memberof Roaming
 */
VFG.Roam.prototype.ChangeRoamingSpeed = function(value) {
    this.viewer.clock.multiplier = value;
}

VFG.Roam.prototype.destroy = function() {
	this.viewer.clock.shouldAnimate = false;
	this.viewer.trackedEntity = null;
	this.viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY)
	if(this.renderListener){
		this.viewer.scene.preRender.removeEventListener(this.renderListener);
	}
	if(this.entity){
		this.viewer.entities.remove(this.entity);
	}
    delete this.option,
    delete this.entity,
    delete this.renderListener,
    delete this.viewer
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="VFGTip.js" />
/*  *  *  *  *  *  *  *  *  *  *
 *     Tip      *
 *  *  *  *  *  *  *  *  *  *  */
!function(e, t) {
	"object" == typeof exports && "object" == typeof module ? module.exports = t(require("Cesium"))
			: "function" == typeof define && define.amd ? define([ "Cesium" ],
					t)
					: "object" == typeof exports ? exports.CesiumMQTT = t(require("Cesium"))
							: e.VFGTip = t(e.Cesium)
}("undefined" != typeof self ? self : this, function(cesium) {
	function _(viewer, options) {
		this.viewer = viewer;
		this.options = options;
		this.frameDiv=this.viewer.cesiumWidget.container;
		this.isInit=false;
		this.init();
	}
	_.prototype.init = function() {
		var _self = this;
	    if (_self.isInit) { return; }
	    var div = document.createElement('DIV');
	    div.className = "toolTip-left";
	    var title = document.createElement('DIV');
	    title.className = "tooltipdiv-inner";
	    div.appendChild(title);
	    _self._div = div;
	    _self._title = title;
	    _self.frameDiv.appendChild(div);
	    _self.isInit = true;
	};
	_.prototype.setVisible = function(visible) {
		var _self = this;
	    if (!_self.isInit) { return; }
	    _self._div.style.display = visible ? 'block' : 'none';
	};
	_.prototype.showAt = function (position, message) {
		var _self = this;
	    if (!_self.isInit) { return; }
	    if (position && message) {
	    	_self.setVisible(true);
	    	_self._title.innerHTML = message;
	    	_self._div.style.position = "absolute"
	    	_self._div.style.left = position.x + 20 + "px";
	    	_self._div.style.top = (position.y - this._div.clientHeight/2) + "px";
	    }
    };
	_.prototype.destroy = function() {
		var _self = this;
		if( _self._div){
			$( _self._div).remove();
		}
		if( _self._title){
			$( _self._title).remove();
		}
		return Cesium.destroyObject(this);
	};
	VFG.Tip = _;
});
///<jscompress sourcefile="VFGVModel.js" />
VFG.VModel = function(viewer,option) {
	this.option = Cesium.defaultValue(option, Cesium.defaultValue.EMPTY_OBJECT);
	this.viewer = Cesium.defaultValue(viewer, undefined);
	if (!viewer) {
		console.log('viewer参数必填!');
		return;
	}
	if (!option) {
		console.log('参数必填!');return;
	}
	
	if(!option.model || !option.model.type=='OBJ' ){
		console.log('参数必填!');return;
	}
	
	
	this.option=option;
	this.primitive;
	this.videoEle;
	
	this.vertices=[];
	this.normals=[];
	this.colors=[];
	this.uvs=[];
	
	this.geometry={
		vertices: [],
		normals: [],
		colors: [],
		uvs: [],
		indices:[],
	}
	this.init();
}

VFG.VModel.prototype.init=function(){
	this.read();
}

VFG.VModel.prototype.read=function(){
	var _this=this;
	var request = new XMLHttpRequest();
	request.onreadystatechange = function() {
		if (request.readyState == 4 && request.status != 404) {
			if(_this.option.onsuccess){
			}
			_this.parse(request.responseText);
			_this.create(_this.geometry);
		}
	};
	request.onerror=function(error){
		if(_this.option.onerror){
			_this.option.onerror(error)
		}
	};
	request.ontimeout=function(error){
		if(_this.option.ontimeout){
			_this.option.ontimeout(error)
		}
	};
	
	if('1' ==_this.option.model.isRelUrl){
		request.open('GET', _this.option.localUrl+_this.option.model.url, true); 
	}else{
		request.open('GET', _this.option.model.url, true); 
	}
	request.send();
}

VFG.VModel.prototype.create=function(geometry){
	var _this=this;
	var normals=geometry.normals;
	var uvs=geometry.uvs;
	var vertices=geometry.vertices;
	var indices=new Uint16Array(geometry.indices);
	
    this.primitive=_this.viewer.scene.primitives.add(new Cesium.Primitive({
        geometryInstances: new Cesium.GeometryInstance({
            geometry: new Cesium.Geometry({
                attributes: {
                    position: new Cesium.GeometryAttribute({
                        componentDatatype: Cesium.ComponentDatatype.DOUBLE,
                        componentsPerAttribute: 3,
                        values: vertices
                    }),
                    normal: new Cesium.GeometryAttribute({
                        componentDatatype: Cesium.ComponentDatatype.FLOAT,
                        componentsPerAttribute: 3,
                        values: normals
                    }),
                    st: new Cesium.GeometryAttribute({
                        componentDatatype: Cesium.ComponentDatatype.FLOAT,
                        componentsPerAttribute: 2,
                        values: uvs
                    }),
                },
               // indices: indices, 
                id:_this.option,
                primitiveType: Cesium.PrimitiveType.TRIANGLES,
                boundingSphere: Cesium.BoundingSphere.fromVertices(vertices),
            }),
        }),
       appearance: new Cesium.MaterialAppearance({
/*            material: new Cesium.Material({ 
	     	     fabric : {
	     		    type : 'Image',
	     		    uniforms : {
	     		      image : _this.option.imgUrl
	     		    }
	     		  }
     		}),*/
    	    material: _this.getMaterial(),
            faceForward : true, 
            closed: false 
        }),
        modelMatrix: _this.getModelMatrix(),
        asynchronous: false
    }));
}

VFG.VModel.prototype.getMaterial = function() {
	var _self = this;
	if(_self.option.video){
		_self.videoEle=_self.createVideoEle();
		_self.canplaythrough=function () {
	    	_self.viewer.clock.onTick.addEventListener(_self.activeVideoListener, _self);
	    };
	    _self.videoEle.addEventListener("canplaythrough",_self.canplaythrough );
	    var material = Cesium.Material.fromType('Image');
	    material.uniforms.image =_self.videoEle;
	    return material;
	}else{
		return new Cesium.Material({
		    fabric : {
		        type : 'Color',
		        uniforms : {
		            color : Cesium.Color.BLACK.withAlpha(0.5)
		        }
		    }
		})
	}
};

VFG.VModel.prototype.createVideoEle = function () {
	var _self = this;
	 var r = document.createElement("VIDEO");
	var src;
	if(_self.option.video && _self.option.video.type=='FILE'){
		src=_self.option.video.url;
	}
	else{
    	_self.webRtcServer= new WebRtcStreamer(r,_self.option.video.url);
	    _self.webRtcServer.connect(_self.option.video.id,'','');
	}
	this.videoId = "visualDomId"+_self.option.id;
    var t = document.createElement("SOURCE");
    t.type = "video/mp4",
    t.src = src;
    var i = document.createElement("SOURCE");
    i.type = "video/quicktime",
    i.src = src;
    return r.setAttribute("autoplay", !0),
    r.setAttribute("loop", !0),
    r.setAttribute("crossorigin", !0),
    r.setAttribute("muted", "muted"),
    r.appendChild(t),
    r.appendChild(i),
    r.style.display = "none",
    document.body.appendChild(r),
    r
}

VFG.VModel.prototype.update = function() {
	var _this = this;
	var modelMatrix=_this.getModelMatrix();
	if(this.primitive){
		this.primitive.modelMatrix=modelMatrix;
	}
};


VFG.VModel.prototype.parse=function( text ) {
	var _this=this;
	if ( text.indexOf( '\r\n' ) !== - 1 ) {
		text = text.replace( /\r\n/g, '\n' );
	}

	if ( text.indexOf( '\\\n' ) !== - 1 ) {
		text = text.replace( /\\\n/g, '' );
	}

	var lines = text.split( '\n' );
	var line = '', lineFirstChar = '';
	var lineLength = 0;
	var result = [];

	// Faster to just trim left side of the line. Use if available.
	var trimLeft = ( typeof ''.trimLeft === 'function' );

	for ( var i = 0, l = lines.length; i < l; i ++ ) {

		line = lines[ i ];
		line = trimLeft ? line.trimLeft() : line.trim();
		lineLength = line.length;
		if ( lineLength === 0 ) continue;

		lineFirstChar = line.charAt( 0 );
		// @todo invoke passed in handler if any
		if ( lineFirstChar === '#' ) continue;

		if ( lineFirstChar === 'v' ) {
			var data = line.split( /\s+/ );
			switch ( data[ 0 ] ) {
				case 'v':
					_this.vertices.push(
						parseFloat( data[ 1 ] ),
						parseFloat( data[ 2 ] ),
						parseFloat( data[ 3 ] )
					);
					if ( data.length >= 7 ) {
						_this.colors.push(
							parseFloat( data[ 4 ] ),
							parseFloat( data[ 5 ] ),
							parseFloat( data[ 6 ] )
						);
					} else {
						_this.colors.push( undefined, undefined, undefined );
					}
					break;
				case 'vn':
					_this.normals.push(
						parseFloat( data[ 1 ] ),
						parseFloat( data[ 2 ] ),
						parseFloat( data[ 3 ] )
					);
					break;
				case 'vt':
					_this.uvs.push(
						parseFloat( data[ 1 ] ),
						parseFloat( data[ 2 ] )
					);
					break;

			}

		} else if ( lineFirstChar === 'f' ) {
			var lineData = line.substr( 1 ).trim();
			var vertexData = lineData.split( /\s+/ );
			var faceVertices = [];

			// Parse the face vertex data into an easy to work with format
			for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
				var vertex = vertexData[ j ];
				if ( vertex.length > 0 ) {
					var vertexParts = vertex.split( '/' );
					faceVertices.push( vertexParts );
					this.geometry.indices.push(vertexParts[0]*1-1);
				}
				
			}
			var v1 = faceVertices[ 0 ];
			for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
				var v2 = faceVertices[ j ];
				var v3 = faceVertices[ j + 1 ];
				_this.addFace(
					v1[ 0 ], v2[ 0 ], v3[ 0 ],
					v1[ 1 ], v2[ 1 ], v3[ 1 ],
					v1[ 2 ], v2[ 2 ], v3[ 2 ]
				);
			}
		} else {
			if ( line === '\0' ) continue;
		}
	}
}

VFG.VModel.prototype.getModelMatrix = function() {
	var _self = this;
	var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(_self.getPosition());
	var scaleMatrix = Cesium.Matrix4.fromScale(_self.getScale());
		modelMatrix = Cesium.Matrix4.multiply(modelMatrix, scaleMatrix, new Cesium.Matrix4());
	var hprRotation = Cesium.Matrix3.fromHeadingPitchRoll(_self.getRotation());
	var hpr = Cesium.Matrix4.fromRotationTranslation(hprRotation,new Cesium.Cartesian3(0.0, 0.0, 0.0));
	return Cesium.Matrix4.multiply(modelMatrix, hpr, modelMatrix);
}; 

VFG.VModel.prototype.getScale = function() {
	var _self = this;
	return new Cesium.Cartesian3(
			_self.option.scaleX?_self.option.scaleX*1:1,
			_self.option.scaleY?_self.option.scaleY*1:1,
			_self.option.scaleZ?_self.option.scaleZ*1:1);
};

VFG.VModel.prototype.addFace= function ( a, b, c, ua, ub, uc, na, nb, nc ) {
	var vLen = this.vertices.length;
	
	var ia = this.parseVertexIndex( a, vLen );
	var ib = this.parseVertexIndex( b, vLen );
	var ic = this.parseVertexIndex( c, vLen );

	this.addVertex( ia, ib, ic );
	this.addColor( ia, ib, ic );
	
	
	 this.geometry.indices.push(ia);
	 this.geometry.indices.push(ib);
	 this.geometry.indices.push(ic);
	

	// normals
	if ( na !== undefined && na !== '' ) {
		var nLen = this.normals.length;
		ia = this.parseNormalIndex( na, nLen );
		ib = this.parseNormalIndex( nb, nLen );
		ic = this.parseNormalIndex( nc, nLen );
		this.addNormal( ia, ib, ic );
	} else {
		this.addFaceNormal( ia, ib, ic );
	}

	// uvs
	if ( ua !== undefined && ua !== '' ) {
		var uvLen = this.uvs.length;
		ia = this.parseUVIndex( ua, uvLen );
		ib = this.parseUVIndex( ub, uvLen );
		ic = this.parseUVIndex( uc, uvLen );
		this.addUV( ia, ib, ic );
	} else {
		this.addDefaultUV();
	}
},

//use
VFG.VModel.prototype.addVertex=function ( a, b, c ) {
	var src = this.vertices;
	var dst = this.geometry.vertices;
	dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
	dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
	dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
},

//use
VFG.VModel.prototype.addNormal=function ( a, b, c ) {
	var src = this.normals;
	var dst = this.geometry.normals;
	dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
	dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
	dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
},

//use
VFG.VModel.prototype.addFaceNormal=function ( a, b, c ) {

	var src = this.vertices;
	var dst = this.geometry.normals;

	vA.fromArray( src, a );
	vB.fromArray( src, b );
	vC.fromArray( src, c );

	cb.subVectors( vC, vB );
	ab.subVectors( vA, vB );
	cb.cross( ab );

	cb.normalize();

	dst.push( cb.x, cb.y, cb.z );
	dst.push( cb.x, cb.y, cb.z );
	dst.push( cb.x, cb.y, cb.z );

},

//use
VFG.VModel.prototype.addColor= function ( a, b, c ) {

	var src = this.colors;
	var dst = this.geometry.colors;

	if ( src[ a ] !== undefined ) dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
	if ( src[ b ] !== undefined ) dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
	if ( src[ c ] !== undefined ) dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );

},

//use
VFG.VModel.prototype.addUV= function ( a, b, c ) {
	var src = this.uvs;
	var dst = this.geometry.uvs;
	dst.push( src[ a + 0 ], src[ a + 1 ] );
	dst.push( src[ b + 0 ], src[ b + 1 ] );
	dst.push( src[ c + 0 ], src[ c + 1 ] );
},

//use
VFG.VModel.prototype.addDefaultUV=function () {
	var dst = this.geometry.uvs;
	dst.push( 0, 0 );
	dst.push( 0, 0 );
	dst.push( 0, 0 );
},

VFG.VModel.prototype.parseVertexIndex=function ( value, len ) {
	var index = parseInt( value, 10 );
	return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
},

VFG.VModel.prototype.parseNormalIndex=function ( value, len ) {
	var index = parseInt( value, 10 );
	return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
},
VFG.VModel.prototype.parseUVIndex=function ( value, len ) {
	var index = parseInt( value, 10 );
	return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
},

VFG.VModel.prototype.getPosition = function() {
	var _self = this;
	return Cesium.Cartesian3.fromDegrees(_self.option.x*1,_self.option.y*1,_self.option.z*1);
};
VFG.VModel.prototype.getRotation = function() {
	var _self = this;
	return new Cesium.HeadingPitchRoll(
		Cesium.Math.toRadians(_self.option.rotationX?_self.option.rotationX*1:0), 
		Cesium.Math.toRadians(_self.option.rotationY?_self.option.rotationY*1:0), 
		Cesium.Math.toRadians(_self.option.rotationZ?_self.option.rotationZ*1:0));
};

VFG.VModel.prototype.activeVideoListener = function (e) {
	var _this=this;
    try {
        if (_this._videoPlay && _this.videoEle.paused) _this.videoEle.play();
    } catch (e) {}
}

VFG.VModel.prototype.deActiveVideo = function (e) {
	this.viewer.clock.onTick.removeEventListener(this.activeVideoListener, this);
}

VFG.VModel.prototype.destroy = function () {
  this.deActiveVideo();
  if(this.primitive){
	  this.viewer.scene.primitives.remove(this.primitive);
  }
  if(this.primitive){
	  this.viewer.scene.primitives.remove(this.primitive);
  }
  
  if(this.videoEle){
	  this.videoEle.removeEventListener('canplaythrough',this.canplaythrough);
  }
  if(this.webRtcServer){
	  this.webRtcServer.disconnect();
  }
  this.videoEle && this.videoEle.parentNode.removeChild(this.videoEle),
  delete this.webRtcServer,
  delete this.videoEle,
  delete this.options,
  delete this.viewer;
  return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="VFGVPlane.js" />
VFG.VPlane=function(viewer,option){
	this.viewer=viewer;
	this.option=option;
	this.primitive;
	this.videoEl;
	this.init();
}

VFG.VPlane.prototype.init = function() {
	var _self = this;
	this.material=_self.getMaterial();
	this.create();
};

VFG.VPlane.prototype.create = function() {
	var _self = this;
	_self.primitive=_self.viewer.scene.primitives.add(new Cesium.Primitive({
		  geometryInstances: new Cesium.GeometryInstance({
		      geometry: Cesium.BoxGeometry.fromDimensions({
			        dimensions: _self.getDimensions(),
		      }),
		      modelMatrix:  _self.getModelMatrix(),
		      id:_self.option,
	    }),
        appearance : new Cesium.MaterialAppearance({
        	closed: false,
        	material: _self.material
        })
   }));
};

VFG.VPlane.prototype.getModelMatrix = function() {
	var _self = this;
	var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(_self.getPosition());
	var hprRotation = Cesium.Matrix3.fromHeadingPitchRoll(_self.getRotation());
	var hpr = Cesium.Matrix4.fromRotationTranslation(hprRotation,new Cesium.Cartesian3(0.0, 0.0, 0.0));
	return Cesium.Matrix4.multiply(modelMatrix, hpr, modelMatrix);
};

VFG.VPlane.prototype.getPosition = function() {
	var _self = this;
	return Cesium.Cartesian3.fromDegrees(_self.option.x*1,_self.option.y*1,_self.option.z*1);
};

VFG.VPlane.prototype.getDimensions = function() {
	var _self = this;
	return new Cesium.Cartesian3(_self.option.dimensionX*1,_self.option.dimensionY*1,_self.option.dimensionZ*1);
};

VFG.VPlane.prototype.getRotation = function() {
	var _self = this;
	return new Cesium.HeadingPitchRoll(
		Cesium.Math.toRadians(_self.option.rotationX?_self.option.rotationX*1:0), 
		Cesium.Math.toRadians(_self.option.rotationY?_self.option.rotationY*1:0), 
		Cesium.Math.toRadians(_self.option.rotationZ?_self.option.rotationZ*1:0));
};

VFG.VPlane.prototype.getMaterial = function() {
	var _self = this;
	_self.videoEl=this.createVideoEle();
    _self.videoEl.addEventListener("canplaythrough", function () {
    	_self.viewer.clock.onTick.addEventListener(_self.activeVideoListener, _self);
    });
    var material = Cesium.Material.fromType('Image');
    material.uniforms.image =_self.videoEl;
    return material;
};

VFG.VPlane.prototype.update = function() {
	if(this.primitive){
		this.viewer.scene.primitives.remove(this.primitive);
	}
	this.create();
};

VFG.VPlane.prototype.activeVideoListener = function() {
	var _self = this;
    try {
        if (this._videoPlay && _self.videoEl.paused) _self.videoEl.play();
    } catch (e) {}
};
VFG.VPlane.prototype.deActiveVideo = function() {
	var _self = this;
	_self.viewer.clock.onTick.removeEventListener(_self.activeVideoListener, _self);
    delete _self.activeVideoListener;
};
VFG.VPlane.prototype.createVideoEle = function () {
	var _self = this;
	var src;
	if(_self.option.video && _self.option.video.type=='FILE'){
		src=_self.option.video.url;
	}
	this.videoId = "visualDomId"+_self.option.id;
    var t = document.createElement("SOURCE");
    t.type = "video/mp4",
    t.src = src;
    var i = document.createElement("SOURCE");
    i.type = "video/quicktime",
    i.src = src;
    var r = document.createElement("VIDEO");
    return r.setAttribute("autoplay", !0),
    r.setAttribute("loop", !0),
    r.setAttribute("crossorigin", !0),
    r.appendChild(t),
    r.appendChild(i),
    r.style.display = "none",
    document.body.appendChild(r),
    r
}

VFG.VPlane.prototype.destroy = function() {
	if(this.primitive){
		this.viewer.scene.primitives.remove(this.primitive);
	}
	this.deActiveVideo();
    this.videoEl && this.videoEl.parentNode.removeChild(this.videoEl),
    delete this.option,
    delete this.viewer
	return Cesium.destroyObject(this);
};
;
///<jscompress sourcefile="VFGVShed3d.js" />
/**
 * 视频投影对象
 */
VFG.VShed3d=function(viewer,options){
    if (!viewer) return;
    if (!options) options = {};
    this.viewer = viewer;
    this.option = options.option; 
    this.video = this.option.video; //视频对象
    this._cameraPosition = options.cameraPosition; // 相机位置
    this._position = options.position; // 视点位置
    this._alpha = options.alpha || 1.0; // 透明度
    this._near = (options.near?options.near*1:0.1)
    this._heading = (options.heading?options.heading*1:0.1)
    this._pitch = (options.pitch?options.pitch*1:0.1)
    this._roll = (options.roll?options.roll*1:0.1)
    this._debugFrustum = Cesium.defaultValue(options.debugFrustum, true); // 显示视椎体
    this._aspectRatio = (options.aspectRatio?options.aspectRatio*1:0.75); // 宽高比
    this._camerafov =(options.fov?Cesium.Math.toRadians(options.fov*1):this.viewer.scene.camera.frustum.fov); // 相机水平张角
    this._maskUrl = this.option.maskUrl;
    this._videoPlay = Cesium.defaultValue(options.videoPlay, true); // 暂停播放
    this.defaultShow = Cesium.defaultValue(options.show, true); // 显示和隐藏
    this.clearBlack = Cesium.defaultValue(options.clearBlack, true); // 消除鱼眼视频的黑色
    this._rotateDeg = 1;
    this._disViewColor = Cesium.defaultValue(options.disViewColor, new Cesium.Color(0, 0, 0, 0.2));
    this._dirObj = Cesium.defaultValue(options.dirObj, undefined);
    if (!this.cameraPosition || !this.position) {
        console.log("初始化失败：请确认相机位置与视点位置正确！");
        return;
    }
    
	var _this=this;
    //视频默认材质
    this.videoTexture =new Cesium.Texture({
        context: this.viewer.scene.context,
        source: {
            width: 1,
            height: 1,
            arrayBufferView: new Uint8Array([255, 255, 255, 255])
        },
        flipY: false
    });
    this.imageTexture = new Cesium.Texture({
		context: this.viewer.scene.context,
        source: {
            width: 1,
            height: 1,
            arrayBufferView: new Uint8Array([255, 255, 255, 255])
        },
        flipY: false
	});
    this.activeImage();
    this.activeVideo();
    this.initProjection();
    this._addPostProcess();
    this.viewer.scene.primitives.add(this);
}

VFG.VShed3d.prototype.activeImage=function(){
	if(this.maskUrl){
		var _this=this;
        Cesium.Resource.createIfNeeded(this.maskUrl).fetchImage().then(function(image) {
            console.log('image loaded!');
            var context = _this.viewer.scene.context;
            if (Cesium.defined(image.internalFormat)) {
            	_this.imageTexture = new Cesium.Texture({
                    context: context,
                    pixelFormat: image.internalFormat,
                    width: image.naturalWidth,
                    height: image.naturalHeight,
                    source: {
                        arrayBufferView: image.bufferView
                    }
                });
            } else {
            	_this.imageTexture = new Cesium.Texture({
                    context: context,
                    source: image
                });
            }
        });
	}else{
	    this.imageTexture = new Cesium.Texture({
			context: this.viewer.scene.context,
	        source: {
	            width: 1,
	            height: 1,
	            arrayBufferView: new Uint8Array([255, 255, 255, 255])
	        },
	        flipY: false
		});
	}
}

VFG.VShed3d.prototype.getPercentagePoint = function(cartesian) {
    if (!cartesian) return;
    var vm = this.viewShadowMap._lightCamera._viewMatrix;
    var pm = this.viewShadowMap._lightCamera.frustum.projectionMatrix;
    var c4 = new Cesium.Cartesian4(cartesian.x, cartesian.y, cartesian.z, 1.0);
    var pvm = Cesium.Matrix4.multiply(pm, vm, new Cesium.Matrix4());
    var epos1 = Cesium.Matrix4.multiplyByVector(pvm, c4, new Cesium.Cartesian4());
    var epos2 = new Cesium.Cartesian2(epos1.x / epos1.w, epos1.y / epos1.w);
    var epos3 = new Cesium.Cartesian2(epos2.x / 2 + 0.5, epos2.y / 2 + 0.5);
    return epos3;
};

// 激活或重置视频URL
VFG.VShed3d.prototype.activeVideo = function() {
	var _this = this;
	this.videoElement = this._createVideoEle();
    if (this.videoElement) {
        this.videoElement.addEventListener("canplaythrough", function () {
        	_this.viewer.clock.onTick.addEventListener(_this.activeVideoListener, _this);
        });
    }
};

//视频播放监听
VFG.VShed3d.prototype.activeVideoListener = function() {
	var _this=this;
    try {
        if (this._videoPlay && this.videoElement.paused) this.videoElement.play();
    } catch (e) {}

    this.videoTexture && this.videoTexture.destroy();
    if(_this.viewer){
        this.videoTexture = new Cesium.Texture({
            context: _this.viewer.scene.context,
            source: this.videoElement,
            pixelFormat: Cesium.PixelFormat.RGBA,
            pixelDatatype: Cesium.PixelDatatype.UNSIGNED_BYTE
        });
    }
};
// 删除视频播放监听
VFG.VShed3d.prototype.deActiveVideo = function() {
    this.viewer.clock.onTick.removeEventListener(this.activeVideoListener, this);
    delete this.activeVideoListener;
};

//创建video元素
VFG.VShed3d.prototype._createVideoEle = function() {
	var src;
	if(this.video && this.video.type=='FILE'){
		src=this.video.url;
	}
    // 创建可视域video DOM 元素
    if (!src) return;
    // this.videoId = 'visualDomId';
    var source_map4 = document.createElement("SOURCE");
    source_map4.type = 'video/mp4';
    source_map4.src = src;
    var source_mov = document.createElement("SOURCE");
    source_mov.type = 'video/quicktime';
    source_mov.src = src;
    var videoEle = document.createElement("video");
    videoEle.setAttribute('autoplay', true);
    videoEle.setAttribute('loop', true);
    videoEle.setAttribute('crossorigin', true);
    videoEle.appendChild(source_map4);
    videoEle.appendChild(source_mov);
    videoEle.style.display = 'none';
    document.body.appendChild(videoEle);
    return videoEle;
};

VFG.VShed3d.prototype.initProjection = function() {
	var _this=this;
	var far=Cesium.Cartesian3.distance(this.position, this.cameraPosition);
    this.viewShadowMap = new Cesium.ShadowMap({
        lightCamera: _this.getCamera(far),
        enable: false,
        isPointLight: false,
        isSpotLight: true,
        cascadesEnabled: false,
        context: this.viewer.scene.context,
        pointLightRadius: far
    });
    
    this.cameraFrustum = new Cesium.Primitive({
        geometryInstances: new Cesium.GeometryInstance({
            geometry: new Cesium.FrustumOutlineGeometry({
                origin: _this.cameraPosition,
                orientation: this._getOrientation(),
                frustum:this.viewShadowMap._lightCamera.frustum,
                _drawNearPlane: true
            }),
            attributes: {
                color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.YELLOW)
            }
        }),
        appearance: new Cesium.PerInstanceColorAppearance({
            translucent: false,
            flat: true
        }),
        asynchronous: false,
        show: this.debugFrustum
    });
    this.viewer.scene.primitives.add(this.cameraFrustum);
};

VFG.VShed3d.prototype.changeProjection = function() {
	var _this=this;
	var far=Cesium.Cartesian3.distance(this.position, this.cameraPosition);
//	if(this.viewShadowMap){
////	    this.viewShadowMap._lightCamera = this.getCamera(far);
////	    this.viewShadowMap._pointLightRadius = far;
//	}
	
    this.viewShadowMap = new Cesium.ShadowMap({
        lightCamera: _this.getCamera(far),
        enable: false,
        isPointLight: false,
        isSpotLight: true,
        cascadesEnabled: false,
        context: this.viewer.scene.context,
        pointLightRadius: far
    });
	
	
	if(this.cameraFrustum){
	   	 this.viewer.scene.primitives.remove(this.cameraFrustum),
		 this.cameraFrustum.destroy();
	}
    this.cameraFrustum = new Cesium.Primitive({
        geometryInstances: new Cesium.GeometryInstance({
            geometry: new Cesium.FrustumOutlineGeometry({
                origin: _this.cameraPosition,
                orientation: this._getOrientation(),
                frustum:this.viewShadowMap._lightCamera.frustum,
                _drawNearPlane: true
            }),
            attributes: {
                color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.YELLOW)
            }
        }),
        appearance: new Cesium.PerInstanceColorAppearance({
            translucent: false,
            flat: true
        }),
        asynchronous: false,
        show: this.debugFrustum 
    });
    this.viewer.scene.primitives.add(this.cameraFrustum);
};

VFG.VShed3d.prototype.setViewPosition = function(position) {
	var _this=this;
	_this._position=position;
};

/**
 * 投影相机
 */
VFG.VShed3d.prototype.getCamera = function(far) {
	var _this=this;
    var camera_pos = this.cameraPosition;
    var lookat_pos = this.position;
    var camera = new Cesium.Camera(this.viewer.scene);
    camera.position = camera_pos;
	camera.direction = Cesium.Cartesian3.subtract(lookat_pos, camera_pos, new Cesium.Cartesian3(0, 0, 0));
	camera.up = Cesium.Cartesian3.normalize(camera_pos, new Cesium.Cartesian3(0, 0, 0));
	
	camera.setView({
	    orientation: {
	        heading : Cesium.Math.toRadians(_this.heading),
	        pitch : Cesium.Math.toRadians(_this.pitch),
	        roll : Cesium.Math.toRadians(_this.roll)
	    }
	});
	
	camera.frustum = new Cesium.PerspectiveFrustum({
        fov: this.fov,
        aspectRatio: this.aspectRatio,
        near: this.near,
        far: far
    });
	return camera;
};

VFG.VShed3d.prototype._switchShow = function() {
    if (this.show) {
        !this.postProcess && this._addPostProcess();
    } else {
        this.viewer.scene.postProcessStages.remove(this.postProcess);
        delete this.postProcess;
        this.postProcess = null;
    }
};

VFG.VShed3d.prototype.update = function (e) {
    this.viewShadowMap && this.viewer.scene.frameState.shadowMaps.push(this.viewShadowMap) // *重点* 多投影
}

//呈现投影相机的第一视角
VFG.VShed3d.prototype.locate = function() {
    var camera_pos = Cesium.clone(this.cameraPosition);
    var lookat_pos = Cesium.clone(this.position);
    this.viewer.camera.position = camera_pos;
    if (this._dirObj) {
        this.viewer.camera.direction = Cesium.clone(this._dirObj.direction);
        this.viewer.camera.right = Cesium.clone(this._dirObj.right);
        this.viewer.camera.up = Cesium.clone(this._dirObj.up);
        return;
    }
    this.viewer.camera.direction = Cesium.Cartesian3.subtract(lookat_pos, camera_pos, new Cesium.Cartesian3(0, 0, 0));
    this.viewer.camera.up = Cesium.Cartesian3.normalize(camera_pos, new Cesium.Cartesian3(0, 0, 0));
};

//获取四元数
VFG.VShed3d.prototype._getOrientation = function() {
    var cpos = this.cameraPosition;
    var position = this.position;
    var direction = Cesium.Cartesian3.normalize(Cesium.Cartesian3.subtract(position, cpos, new Cesium.Cartesian3()), new Cesium.Cartesian3());
    var up = Cesium.Cartesian3.normalize(cpos, new Cesium.Cartesian3());
    var camera = new Cesium.Camera(this.viewer.scene);
    camera.position = cpos;
    camera.direction = direction;
    camera.up = up;
    
	camera.setView({
	    orientation: {
	        heading : Cesium.Math.toRadians(this.heading),
	        pitch : Cesium.Math.toRadians(this.pitch),
	        roll : Cesium.Math.toRadians(this.roll)
	    }
	});
    
    direction = camera.directionWC;
    up = camera.upWC;
    var right = camera.rightWC;
    var scratchRight = new Cesium.Cartesian3();
    var scratchRotation = new Cesium.Matrix3();
    var scratchOrientation = new Cesium.Quaternion();

    right = Cesium.Cartesian3.negate(right, scratchRight);
    var rotation = scratchRotation;
    Cesium.Matrix3.setColumn(rotation, 0, right, rotation);
    Cesium.Matrix3.setColumn(rotation, 1, up, rotation);
    Cesium.Matrix3.setColumn(rotation, 2, direction, rotation);
    // 计算视锥姿态
    var orientation = Cesium.Quaternion.fromRotationMatrix(rotation, scratchOrientation);
    this.orientation = orientation;
    return orientation;
};
// 添加后处理
VFG.VShed3d.prototype._addPostProcess = function() {
    var that = this;
    var bias = that.viewShadowMap._isPointLight ? that.viewShadowMap._pointBias : that.viewShadowMap._primitiveBias;
    if (!this.show) return;
    var fragmentShader='\r\n\r\n\r\n\r\nuniform\x20float\x20mixNum;\x0auniform\x20sampler2D\x20colorTexture;\x0auniform\x20sampler2D\x20shadowMapTexture;\x0auniform\x20sampler2D\x20videoTexture;\x0auniform\x20sampler2D\x20maskTexture;\x0auniform\x20sampler2D\x20depthTexture;\x0auniform\x20mat4\x20shadowMap_matrix;\x0auniform\x20vec4\x20shadowMap_lightPositionEC;\x0auniform\x20vec4\x20shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness;\x0auniform\x20vec4\x20shadowMap_texelSizeDepthBiasAndNormalShadingSmooth;\x0auniform\x20vec4\x20disViewColor;\x0auniform\x20bool\x20clearBlack;\x0avarying\x20vec2\x20v_textureCoordinates;\x0a\x0avec4\x20toEye(in\x20vec2\x20uv,\x20in\x20float\x20depth){\x0a\x20\x20vec2\x20xy\x20=\x20vec2((uv.x\x20*\x202.0\x20-\x201.0),(uv.y\x20*\x202.0\x20-\x201.0));\x0a\x20\x20vec4\x20posInCamera\x20=czm_inverseProjection\x20*\x20vec4(xy,\x20depth,\x201.0);\x0a\x20\x20posInCamera\x20=posInCamera\x20/\x20posInCamera.w;\x0a\x20\x20return\x20posInCamera;\x0a}\x0a\x0afloat\x20getDepth(in\x20vec4\x20depth){\x0a\x20\x20float\x20z_window\x20=\x20czm_unpackDepth(depth);\x0a\x20\x20z_window\x20=\x20czm_reverseLogDepth(z_window);\x0a\x20\x20float\x20n_range\x20=\x20czm_depthRange.near;\x0a\x20\x20float\x20f_range\x20=\x20czm_depthRange.far;\x0a\x20\x20return\x20(2.0\x20*\x20z_window\x20-\x20n_range\x20-\x20f_range)\x20/\x20(f_range\x20-\x20n_range);\x0a}\x0a\x0afloat\x20_czm_sampleShadowMap(sampler2D\x20shadowMap,\x20vec2\x20uv){\x0a\x20\x20return\x20texture2D(shadowMap,\x20uv).r;\x0a}\x0a\x0afloat\x20_czm_shadowDepthCompare(sampler2D\x20shadowMap,\x20vec2\x20uv,\x20float\x20depth){\x0a\x20\x20return\x20step(depth,\x20_czm_sampleShadowMap(shadowMap,\x20uv));\x0a}\x0a\x0afloat\x20_czm_shadowVisibility(sampler2D\x20shadowMap,\x20czm_shadowParameters\x20shadowParameters){\x0a\x20\x20float\x20depthBias\x20=\x20shadowParameters.depthBias;\x0a\x20\x20float\x20depth\x20=\x20shadowParameters.depth;\x0a\x20\x20float\x20nDotL\x20=\x20shadowParameters.nDotL;\x0a\x20\x20float\x20normalShadingSmooth\x20=\x20shadowParameters.normalShadingSmooth;\x0a\x20\x20float\x20darkness\x20=\x20shadowParameters.darkness;\x0a\x20\x20vec2\x20uv\x20=\x20shadowParameters.texCoords;\x0a\x20\x20depth\x20-=\x20depthBias;\x0a\x20\x20vec2\x20texelStepSize\x20=\x20shadowParameters.texelStepSize;\x0a\x20\x20float\x20radius\x20=\x201.0;\x0a\x20\x20float\x20dx0\x20=\x20-texelStepSize.x\x20*\x20radius;\x0a\x20\x20float\x20dy0\x20=\x20-texelStepSize.y\x20*\x20radius;\x0a\x20\x20float\x20dx1\x20=\x20texelStepSize.x\x20*\x20radius;\x0a\x20\x20float\x20dy1\x20=\x20texelStepSize.y\x20*\x20radius;\x0a\x20\x20float\x20visibility\x20=\x0a\x20\x20(\x0a\x20\x20_czm_shadowDepthCompare(shadowMap,\x20uv,\x20depth)\x0a\x20\x20+_czm_shadowDepthCompare(shadowMap,\x20uv\x20+\x20vec2(dx0,\x20dy0),\x20depth)\x20+\x0a\x20\x20_czm_shadowDepthCompare(shadowMap,\x20uv\x20+\x20vec2(0.0,\x20dy0),\x20depth)\x20+\x0a\x20\x20_czm_shadowDepthCompare(shadowMap,\x20uv\x20+\x20vec2(dx1,\x20dy0),\x20depth)\x20+\x0a\x20\x20_czm_shadowDepthCompare(shadowMap,\x20uv\x20+\x20vec2(dx0,\x200.0),\x20depth)\x20+\x0a\x20\x20_czm_shadowDepthCompare(shadowMap,\x20uv\x20+\x20vec2(dx1,\x200.0),\x20depth)\x20+\x0a\x20\x20_czm_shadowDepthCompare(shadowMap,\x20uv\x20+\x20vec2(dx0,\x20dy1),\x20depth)\x20+\x0a\x20\x20_czm_shadowDepthCompare(shadowMap,\x20uv\x20+\x20vec2(0.0,\x20dy1),\x20depth)\x20+\x0a\x20\x20_czm_shadowDepthCompare(shadowMap,\x20uv\x20+\x20vec2(dx1,\x20dy1),\x20depth)\x0a\x20\x20)\x20*\x20(1.0\x20/\x209.0)\x0a\x20\x20;\x0a\x20\x20return\x20visibility;\x0a}\x0a\x0avec3\x20pointProjectOnPlane(in\x20vec3\x20planeNormal,\x20in\x20vec3\x20planeOrigin,\x20in\x20vec3\x20point){\x0a\x20\x20vec3\x20v01\x20=\x20point\x20-planeOrigin;\x0a\x20\x20float\x20d\x20=\x20dot(planeNormal,\x20v01)\x20;\x0a\x20\x20return\x20(point\x20-\x20planeNormal\x20*\x20d);\x0a}\x0a\x0afloat\x20ptm(vec3\x20pt){\x0a\x20\x20return\x20sqrt(pt.x*pt.x\x20+\x20pt.y*pt.y\x20+\x20pt.z*pt.z);\x0a}\x0a\x0a\x0avoid\x20main()\x0a{\x0a\x20\x20const\x20float\x20PI\x20=\x203.141592653589793;\x0a\x20\x20vec4\x20color\x20=\x20texture2D(colorTexture,\x20v_textureCoordinates);\x0a\x20\x20vec4\x20currD\x20=\x20texture2D(depthTexture,\x20v_textureCoordinates);\x0a\x0a\x20\x20if(currD.r>=1.0){\x0a\x20\x20\x20\x20gl_FragColor\x20=\x20color;\x0a\x20\x20\x20\x20return;\x0a\x20\x20}\x0a\x0a\x20\x20float\x20depth\x20=\x20getDepth(currD);\x0a\x20\x20vec4\x20positionEC\x20=\x20toEye(v_textureCoordinates,\x20depth);\x0a\x20\x20vec3\x20normalEC\x20=\x20vec3(1.0);\x0a\x20\x20czm_shadowParameters\x20shadowParameters;\x0a\x20\x20shadowParameters.texelStepSize\x20=\x20shadowMap_texelSizeDepthBiasAndNormalShadingSmooth.xy;\x0a\x20\x20shadowParameters.depthBias\x20=\x20shadowMap_texelSizeDepthBiasAndNormalShadingSmooth.z;\x0a\x20\x20shadowParameters.normalShadingSmooth\x20=\x20shadowMap_texelSizeDepthBiasAndNormalShadingSmooth.w;\x0a\x20\x20shadowParameters.darkness\x20=\x20shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness.w;\x0a\x20\x20shadowParameters.depthBias\x20*=\x20max(depth\x20*\x200.01,\x201.0);\x0a\x20\x20vec3\x20directionEC\x20=\x20normalize(positionEC.xyz\x20-\x20shadowMap_lightPositionEC.xyz);\x0a\x20\x20float\x20nDotL\x20=\x20clamp(dot(normalEC,\x20-directionEC),\x200.0,\x201.0);\x0a\x20\x20vec4\x20shadowPosition\x20=\x20shadowMap_matrix\x20*\x20positionEC;\x0a\x20\x20shadowPosition\x20/=\x20shadowPosition.w;\x0a\x20\x20if\x20(any(lessThan(shadowPosition.xyz,\x20vec3(0.0)))\x20||\x20any(greaterThan(shadowPosition.xyz,\x20vec3(1.0))))\x20{\x0a\x20\x20\x20\x20gl_FragColor\x20=\x20color;\x0a\x20\x20\x20\x20return;\x0a\x20\x20}\x0a\x0a\x20\x20shadowParameters.texCoords\x20=\x20shadowPosition.xy;\x0a\x20\x20shadowParameters.depth\x20=\x20shadowPosition.z;\x0a\x20\x20shadowParameters.nDotL\x20=\x20nDotL;\x0a\x20\x20float\x20visibility\x20=\x20_czm_shadowVisibility(shadowMapTexture,\x20shadowParameters);\x0a\x20\x20vec4\x20videoColor\x20=\x20texture2D(videoTexture,shadowPosition.xy);\x0a\x20\x20vec4\x20maskColor\x20=\x20texture2D(maskTexture,shadowPosition.xy);\x0a\x20\x20videoColor\x20*=\x20maskColor;\x0a\x0a\x20\x20if(clearBlack){\x0a\x20\x20\x20\x20if(videoColor.r\x20+\x20videoColor.g\x20+\x20videoColor.b\x20<0.01){\x0a\x20\x20\x20\x20\x20\x20gl_FragColor\x20=\x20color;\x0a\x20\x20\x20\x20\x20\x20return;\x0a\x20\x20\x20\x20}\x0a\x20\x20}\x0a\x0a\x20\x20if(visibility\x20==\x201.0){\x0a\x20\x20\x20\x20gl_FragColor\x20=\x20mix(color,vec4(videoColor.xyz,1.0),mixNum*videoColor.a);\x0a\x20\x20}else{\x0a\x20\x20\x20\x20if(abs(shadowPosition.z-0.0)<0.01){\x0a\x20\x20\x20\x20\x20\x20return;\x0a\x20\x20\x20\x20}\x0a\x20\x20\x20\x20if(clearBlack){\x0a\x20\x20\x20\x20\x20\x20gl_FragColor\x20=\x20color;\x0a\x20\x20\x20\x20\x20\x20return;\x0a\x20\x20\x20\x20}\x0a\x20\x20\x20\x20gl_FragColor\x20=\x20vec4(mix(color.rgb,disViewColor.rgb,disViewColor.a),disViewColor.a);\x0a\x20\x20}\x0a}';
    this.postProcess = new Cesium.PostProcessStage({
        fragmentShader:fragmentShader,
        uniforms: {
        	mixNum: function mixNum() {
                return that.alpha;
            },
            marsShadow: function marsShadow() {
                return that.viewShadowMap._shadowMapTexture;
            },
            videoTexture: function videoTexture() {
                return that.videoTexture;
            },
            maskTexture: function() {
				return that.imageTexture;
			},
			shadowMapTexture: function() {
				return  that.viewShadowMap._shadowMapTexture;
			},
			shadowMap_matrix: function _shadowMap_matrix() {
                return that.viewShadowMap._shadowMapMatrix;
            },
            shadowMap_lightPositionEC: function shadowMap_lightPositionEC() {
                return that.viewShadowMap._lightPositionEC;
            },
            shadowMap_texelSizeDepthBiasAndNormalShadingSmooth: function shadowMap_texelSizeDepthBiasAndNormalShadingSmooth() {
                var texelStepSize = new Cesium.Cartesian2();
                texelStepSize.x = 1.0 / that.viewShadowMap._textureSize.x;
                texelStepSize.y = 1.0 / that.viewShadowMap._textureSize.y;
                return Cesium.Cartesian4.fromElements(texelStepSize.x, texelStepSize.y, bias.depthBias, bias.normalShadingSmooth, this.combinedUniforms1);
            },
            shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness: function shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness() {
                return Cesium.Cartesian4.fromElements(bias.normalOffsetScale, that.viewShadowMap._distance, that.viewShadowMap.maximumDistance, that.viewShadowMap._darkness, this.combinedUniforms2);
            },
            disViewColor: function disViewColor() {
                return that._disViewColor;
            },
            clearBlack: function clearBlack() {
                return that.clearBlack;
            }
        }
    });
    this.viewer.scene.postProcessStages.add(this.postProcess);
};

VFG.VShed3d.prototype.destroy = function() {
    this.viewer.scene.postProcessStages.remove(this.postProcess);
    if(this.viewShadowMap){
    	this.viewShadowMap.destroy();
    }
    
    if(this.cameraFrustum){
    	this.viewer.scene.primitives.remove(this.cameraFrustum);
    	this.cameraFrustum.destroy();
    }
    this.videoElement && this.videoElement.parentNode.removeChild(this.videoElement);
    this.activeVideoListener && this.viewer.clock.onTick.removeEventListener(this.activeVideoListener),
    this.activeVideoListener && delete this.activeVideoListener,
    delete this.videoElement;
    delete this.activeVideoListener;
    delete this.postProcess;
    delete this.viewShadowMap;
    delete this.color;
    delete this.viewDis;
    delete this._cameraPosition;
    delete this._osition;
    delete this._alpha;
    delete this._camerafov;
    delete this._cameraPosition;
    delete this.videoTexture;
    delete this.cameraFrustum;
    delete this._debugFrustum;
    delete this._position;
    delete this._aspectRatio;
    delete this.orientation;
    delete this.videoTexture;
    delete this.imageTexture;
    delete this._maskUrl;
    this.viewer.scene.primitives.remove(this);
    delete this.viewer;
};
Object.defineProperties(VFG.VShed3d.prototype, {
	alpha: {
        get: function () {
        	 return this._alpha;
        },
        set: function (val) {
        	 this._alpha = val;
        }
    },
    aspectRatio: { // 相机宽高比例
        get: function () {
            return this._aspectRatio;
        },
        set: function (val) {
            this._aspectRatio = val;
            this.changeProjection();
        }
    },
    debugFrustum: {// 视椎体显隐
        get: function () {
        	return this._debugFrustum;
        },
        set: function (val) {
            this._debugFrustum = val;
            this.cameraFrustum.show = val;
        }
    },
    fov: { // 相机水平张角
        get: function () {
        	return this._camerafov;
        },
        set: function (val) {
            this._camerafov = Cesium.Math.toRadians(val);
            this.changeProjection();
        }
    },
    near: { // 相机水平张角
        get: function () {
        	return this._near;
        },
        set: function (val) {
            this._near = val;
            this.changeProjection();
        }
    },
    heading: { // 相机水平张角
        get: function () {
        	return this._heading;
        },
        set: function (val) {
            this._heading = val;
            this.changeProjection();
        }
    },
    pitch: { // 相机水平张角
        get: function () {
        	return this._pitch;
        },
        set: function (val) {
            this._pitch = val;
            this.changeProjection();
        }
    },
    roll: { // 相机水平张角
        get: function () {
        	return this._roll;
        },
        set: function (val) {
            this._roll = val;
            this.changeProjection();
        }
    },
    cameraPosition: { // 相机位置
        get: function () {
        	 return this._cameraPosition;
        },
        set: function (pos) {
            if (!pos) return;
            this._cameraPosition = pos;
            this.changeProjection();
        }
    },
    position: {// 视点位置
        get: function () {
        	return this._position;
        },
        set: function (pos) {
            if (!pos) return;
            this._position = pos;
            this.changeProjection();
        }
    },
    videoPlay: { // 切换视频 播放/暂停
        get: function () {
        	 return this._videoPlay;
        },
        set: function (val) {
            this._videoPlay = Boolean(val);
            if (this.videoElement) {
                if (this.videoPlay) this.videoElement.play();else this.videoElement.pause();
            }
        }
    },
    show: {
        get: function () {
        	return this.defaultShow;
        },
        set: function (val) {
            this.defaultShow = Boolean(val);
            this._switchShow();
        }
    },
    camera: {
        get: function () {
            return this.viewShadowMap._lightCamera;
        }
    },
    disViewColor: {
        get: function () {
        	 return this._disViewColor;
        },
        set: function (color) {
            if (!color) return;
            this._disViewColor = color;
            if (!color.a && color.a != 0) {
                this._disViewColor.a = 1.0;
            }
        }
    },
    maskUrl:{
        get: function () {
       	 	return this._maskUrl;
       },
       set: function (value) {
			this._maskUrl = value;
			this.activeImage();
       }
    }
})

//
//`
// uniform
// float mixNum;
// uniform sampler2D colorTexture;
// uniform sampler2D shadowMapTexture;
// uniform sampler2D videoTexture;
// uniform sampler2D maskTexture;
// uniform sampler2D depthTexture;
// uniform mat4 shadowMap_matrix;
// uniform vec4 shadowMap_lightPositionEC;
// uniform vec4 shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness;
// uniform vec4 shadowMap_texelSizeDepthBiasAndNormalShadingSmooth;
// uniform vec4 disViewColor;
// uniform bool clearBlack;
// varying vec2 v_textureCoordinates;
// vec4 toEye(in vec2 uv, in float depth){
//      vec2 xy = vec2((uv.x * 2.0 - 1.0),(uv.y * 2.0 - 1.0));
//      vec4 posInCamera =czm_inverseProjection * vec4(xy, depth, 1.0);
//      posInCamera =posInCamera / posInCamera.w;
//      return posInCamera;
// }
// float getDepth(in vec4 depth){
//  	float z_window = czm_unpackDepth(depth);
//  	z_window = czm_reverseLogDepth(z_window);
//  	float n_range = czm_depthRange.near;
//  	float f_range = czm_depthRange.far;
//  	return (2.0 * z_window - n_range - f_range) / (f_range - n_range); 
// }  
// float _czm_sampleShadowMap(sampler2D shadowMap, vec2 uv){      
//  	return texture2D(shadowMap, uv).r; 
// }  
// float _czm_shadowDepthCompare(sampler2D shadowMap, vec2 uv, float depth){      
//  	return step(depth, _czm_sampleShadowMap(shadowMap, uv));
// }  
// float _czm_shadowVisibility(sampler2D shadowMap, czm_shadowParameters shadowParameters){      
//	float depthBias = shadowParameters.depthBias;     
//	float depth = shadowParameters.depth;      
//	float nDotL = shadowParameters.nDotL;      
//	float normalShadingSmooth = shadowParameters.normalShadingSmooth;
//  	float darkness = shadowParameters.darkness;
//  	vec2 uv = shadowParameters.texCoords;
//  	depth -= depthBias;
//  	vec2 texelStepSize = shadowParameters.texelStepSize;
//  	float radius = 1.0;
//  	float dx0 = -texelStepSize.x * radius;
//	float dy0 = -texelStepSize.y * radius;
//	float dx1 = texelStepSize.x * radius;
//	float dy1 = texelStepSize.y * radius;
//    float visibility =(_czm_shadowDepthCompare(shadowMap, uv, depth)  +
//       _czm_shadowDepthCompare(shadowMap, uv + vec2(dx0, dy0), depth)  +     
//       _czm_shadowDepthCompare(shadowMap, uv + vec2(0.0, dy0), depth) +      
//       _czm_shadowDepthCompare(shadowMap, uv + vec2(dx1, dy0), depth) +     
//       _czm_shadowDepthCompare(shadowMap, uv + vec2(dx0, 0.0), depth) +      
//       _czm_shadowDepthCompare(shadowMap, uv + vec2(dx1, 0.0), depth) +      
//       _czm_shadowDepthCompare(shadowMap, uv + vec2(dx0, dy1), depth) +      
//       _czm_shadowDepthCompare(shadowMap, uv + vec2(0.0, dy1), depth) +      
//       _czm_shadowDepthCompare(shadowMap, uv + vec2(dx1, dy1), depth)) * (1.0 / 9.0);      
//     return visibility; 
//  }  
//  vec3 pointProjectOnPlane(in vec3 planeNormal, in vec3 planeOrigin, in vec3 point){      
//     vec3 v01 = point -planeOrigin;      
//     float d = dot(planeNormal, v01) ;      
//     return (point - planeNormal * d); 
//  }  
//  float ptm(vec3 pt){      
//  	return sqrt(pt.x*pt.x + pt.y*pt.y + pt.z*pt.z); 
//  }   
//  void main() {      
//      const float PI = 3.141592653589793;      
//      vec4 color = texture2D(colorTexture, v_textureCoordinates);      
//      vec4 currD = texture2D(depthTexture, v_textureCoordinates);       
//      if(currD.r>=1.0){       
//      	gl_FragColor = color;       
//      	return;      
//      }       
//      float depth = getDepth(currD);      
//      vec4 positionEC = toEye(v_textureCoordinates, depth);      
//      vec3 normalEC = vec3(1.0);      
//      czm_shadowParameters shadowParameters;      
//      shadowParameters.texelStepSize = shadowMap_texelSizeDepthBiasAndNormalShadingSmooth.xy;      
//      shadowParameters.depthBias = shadowMap_texelSizeDepthBiasAndNormalShadingSmooth.z;      
//      shadowParameters.normalShadingSmooth = shadowMap_texelSizeDepthBiasAndNormalShadingSmooth.w;      
//      shadowParameters.darkness = shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness.w;      
//      shadowParameters.depthBias *= max(depth * 0.01, 1.0);      
//      vec3 directionEC = normalize(positionEC.xyz - shadowMap_lightPositionEC.xyz);      
//      float nDotL = clamp(dot(normalEC, -directionEC), 0.0, 1.0);      
//      vec4 shadowPosition = shadowMap_matrix * positionEC;      shadowPosition = shadowPosition.w;      
//      if (any(lessThan(shadowPosition.xyz, vec3(0.0))) || any(greaterThan(shadowPosition.xyz, vec3(1.0)))) {       
//      	gl_FragColor = color;       
//      	return;      
//      }       
//      shadowParameters.texCoords = shadowPosition.xy;      
//      shadowParameters.depth = shadowPosition.z;      
//      shadowParameters.nDotL = nDotL;      
//      float visibility = _czm_shadowVisibility(shadowMapTexture, shadowParameters);      
//      vec4 videoColor = texture2D(videoTexture,shadowPosition.xy);      
//      vec4 maskColor = texture2D(maskTexture,shadowPosition.xy);      
//      videoColor *= maskColor;       
//      if(clearBlack){       
//      	if(videoColor.r + videoColor.g + videoColor.b <0.01){       
//       		gl_FragColor = color;        
//       		return;       
//   		}      
//      }      
//	  
//	  if(visibility == 1.0){       
//		gl_FragColor = mix(color,vec4(videoColor.xyz,1.0),mixNum*videoColor.a);
//      }else{
//		if(abs(shadowPosition.z-0.0)<0.01){
//			return;       
//		}
//       if(clearBlack){
//        	gl_FragColor = color;
//        	return;       
//		}       
//		gl_FragColor = vec4(mix(color.rgb,disViewColor.rgb,disViewColor.a),disViewColor.a);
//      } 
//}
// ` 
;
///<jscompress sourcefile="VFGHeatmapImageryProvider.js" />
// /*
//  *  How to add HeatmapImageryProvider to Cesium:
//  *  
//  *  1. Add the class (define - return HeatmapImageryProvider) to Cesium.js after the definition of define and before the definition of Cesium.
//  *  2. Add './Scene/HeatmapImageryProvider' as the first value in the second parameter of the definition call of Cesium (on the line starting with "define('Cesium',[").
//  *  3. Add 'Scene_HeatmapImageryProvider' as the first value in the third parameter of the definition call of Cesium (on the line starting with "define('Cesium',[").
//  *  4. Add 'Cesium['HeatmapImageryProvider'] = Scene_HeatmapImageryProvider;' to the body of the definition call of Cesium (after the line starting with "var Cesium = {").
//  *  5. Make sure heatmap.js in included and available before using HeatmapImageryProvider.
//  *
//  */

// /*global define*/
// define('Scene/HeatmapImageryProvider',[
//         '../Core/Credit',
//         '../Core/defaultValue',
//         '../Core/defined',
//         '../Core/defineProperties',
//         '../Core/DeveloperError',
//         '../Core/Event',
//         '../Core/GeographicTilingScheme',
//         '../Core/Rectangle',
//         '../Core/TileProviderError'
//     ], function(
//         Credit,
//         defaultValue,
//         defined,
//         defineProperties,
//         DeveloperError,
//         Event,
//         GeographicTilingScheme,
//         Rectangle,
//         TileProviderError) {
//     "use strict";

//     /**
//      * Provides a single, top-level imagery tile.  The single image is assumed to use a
//      * {@link GeographicTilingScheme}.

//      *
//      * @alias HeatmapImageryProvider
//      * @constructor
//      *
//      * @param {Object} options Object with the following properties:
//      * @param {Object} [options.heatmapoptions] Optional heatmap.js options to be used (see http://www.patrick-wied.at/static/heatmapjs/docs.html#h337-create).
//      * @param {Object} [options.bounds] The bounding box for the heatmap in WGS84 coordinates.
//      * @param {Number} [options.bounds.north] The northernmost point of the heatmap.
//      * @param {Number} [options.bounds.south] The southernmost point of the heatmap.
//      * @param {Number} [options.bounds.west] The westernmost point of the heatmap.
//      * @param {Number} [options.bounds.east] The easternmost point of the heatmap.
//      * @param {Object} [options.data] Data to be used for the heatmap.
//      * @param {Object} [options.data.min] Minimum allowed point value.
//      * @param {Object} [options.data.max] Maximum allowed point value.
//      * @param {Array} [options.data.points] The data points for the heatmap containing x=lon, y=lat and value=number.
//      *
//      * @see HeatmapImageryProvider
//      * @see ArcGisMapServerImageryProvider
//      * @see BingMapsImageryProvider
//      * @see GoogleEarthImageryProvider
//      * @see OpenStreetMapImageryProvider
//      * @see TileMapServiceImageryProvider
//      * @see WebMapServiceImageryProvider
//      */
//     var HeatmapImageryProvider = function(options) {
//         options = defaultValue(options, {});
//         var bounds = options.bounds;
//         var data = options.data;

//         if (!defined(bounds)) {
//             throw new DeveloperError('options.bounds is required.');
//         } else if (!defined(bounds.north) || !defined(bounds.south) || !defined(bounds.east) || !defined(bounds.west)) {
//             throw new DeveloperError('options.bounds.north, options.bounds.south, options.bounds.east and options.bounds.west are required.');
//         }

//         if (!defined(data)) {
//             throw new DeveloperError('data is required.');
//         } else if (!defined(data.min) || !defined(data.max) || !defined(data.points)) {
//             throw new DeveloperError('options.bounds.north, bounds.south, bounds.east and bounds.west are required.');
//         }

//         this._wmp = new Cesium.WebMercatorProjection();
//         this._mbounds = this.wgs84ToMercatorBB(bounds);
//         this._options = defaultValue(options.heatmapoptions, {});
//         this._options.gradient = defaultValue(this._options.gradient, { 0.25: "rgb(0,0,255)", 0.55: "rgb(0,255,0)", 0.85: "yellow", 1.0: "rgb(255,0,0)"});

//         this._setWidthAndHeight(this._mbounds);
//         this._options.radius = Math.round(defaultValue(this._options.radius, ((this.width > this.height) ? this.width / 60 : this.height / 60)));

//         this._spacing = this._options.radius * 1.5;
//         this._xoffset = this._mbounds.west;
//         this._yoffset = this._mbounds.south;

//         this.width = Math.round(this.width + this._spacing * 2);
//         this.height = Math.round(this.height + this._spacing * 2);

//         this._mbounds.west -= this._spacing * this._factor;
//         this._mbounds.east += this._spacing * this._factor;
//         this._mbounds.south -= this._spacing * this._factor;
//         this._mbounds.north += this._spacing * this._factor;

//         this.bounds = this.mercatorToWgs84BB(this._mbounds);

//         this._container = this._getContainer(this.width, this.height);
//         this._options.container = this._container;
//         this._heatmap = h337.create(this._options);
//         this._canvas = this._container.children[0];

//         this._tilingScheme = new Cesium.WebMercatorTilingScheme({
//             rectangleSouthwestInMeters: new Cesium.Cartesian2(this._mbounds.west, this._mbounds.south),
//             rectangleNortheastInMeters: new Cesium.Cartesian2(this._mbounds.east, this._mbounds.north)
//         });

//         this._image = this._canvas;
//         this._texture = undefined;
//         this._tileWidth = this.width;
//         this._tileHeight = this.height;
//         this._ready = false;

//         if (options.data) {
//             this._ready = this.setWGS84Data(options.data.min, options.data.max, options.data.points);
//         }
//     };

//     defineProperties(HeatmapImageryProvider.prototype, {
//         /**
//          * Gets the URL of the single, top-level imagery tile.
//          * @memberof HeatmapImageryProvider.prototype
//          * @type {String}
//          * @readonly
//          */
//         url : {
//             get : function() {
//                 return this._url;
//             }
//         },

//         /**
//          * Gets the width of each tile, in pixels. This function should
//          * not be called before {@link HeatmapImageryProvider#ready} returns true.
//          * @memberof HeatmapImageryProvider.prototype
//          * @type {Number}
//          * @readonly
//          */
//         tileWidth : {
//             get : function() {
//                 if (!this._ready) {
//                     throw new DeveloperError('tileWidth must not be called before the imagery provider is ready.');
//                 }

//                 return this._tileWidth;
//             }
//         },

//         /**
//          * Gets the height of each tile, in pixels.  This function should
//          * not be called before {@link HeatmapImageryProvider#ready} returns true.
//          * @memberof HeatmapImageryProvider.prototype
//          * @type {Number}
//          * @readonly
//          */
//         tileHeight: {
//             get : function() {
//                 if (!this._ready) {
//                     throw new DeveloperError('tileHeight must not be called before the imagery provider is ready.');
//                 }

//                 return this._tileHeight;
//             }
//         },

//         /**
//          * Gets the maximum level-of-detail that can be requested.  This function should
//          * not be called before {@link HeatmapImageryProvider#ready} returns true.
//          * @memberof HeatmapImageryProvider.prototype
//          * @type {Number}
//          * @readonly
//          */
//         maximumLevel : {
//             get : function() {
//                 if (!this._ready) {
//                     throw new DeveloperError('maximumLevel must not be called before the imagery provider is ready.');
//                 }

//                 return 0;
//             }
//         },

//         /**
//          * Gets the minimum level-of-detail that can be requested.  This function should
//          * not be called before {@link HeatmapImageryProvider#ready} returns true.
//          * @memberof HeatmapImageryProvider.prototype
//          * @type {Number}
//          * @readonly
//          */
//         minimumLevel : {
//             get : function() {
//                 if (!this._ready) {
//                     throw new DeveloperError('minimumLevel must not be called before the imagery provider is ready.');
//                 }

//                 return 0;
//             }
//         },

//         /**
//          * Gets the tiling scheme used by this provider.  This function should
//          * not be called before {@link HeatmapImageryProvider#ready} returns true.
//          * @memberof HeatmapImageryProvider.prototype
//          * @type {TilingScheme}
//          * @readonly
//          */
//         tilingScheme : {
//             get : function() {
//                 if (!this._ready) {
//                     throw new DeveloperError('tilingScheme must not be called before the imagery provider is ready.');
//                 }

//                 return this._tilingScheme;
//             }
//         },

//         /**
//          * Gets the rectangle, in radians, of the imagery provided by this instance.  This function should
//          * not be called before {@link HeatmapImageryProvider#ready} returns true.
//          * @memberof HeatmapImageryProvider.prototype
//          * @type {Rectangle}
//          * @readonly
//          */
//         rectangle : {
//             get : function() {
//                 return this._tilingScheme.rectangle;//TODO: change to custom rectangle?
//             }
//         },

//         /**
//          * Gets the tile discard policy.  If not undefined, the discard policy is responsible
//          * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
//          * returns undefined, no tiles are filtered.  This function should
//          * not be called before {@link HeatmapImageryProvider#ready} returns true.
//          * @memberof HeatmapImageryProvider.prototype
//          * @type {TileDiscardPolicy}
//          * @readonly
//          */
//         tileDiscardPolicy : {
//             get : function() {
//                 if (!this._ready) {
//                     throw new DeveloperError('tileDiscardPolicy must not be called before the imagery provider is ready.');
//                 }

//                 return undefined;
//             }
//         },

//         /**
//          * Gets an event that is raised when the imagery provider encounters an asynchronous error.  By subscribing
//          * to the event, you will be notified of the error and can potentially recover from it.  Event listeners
//          * are passed an instance of {@link TileProviderError}.
//          * @memberof HeatmapImageryProvider.prototype
//          * @type {Event}
//          * @readonly
//          */
//         errorEvent : {
//             get : function() {
//                 return this._errorEvent;
//             }
//         },

//         /**
//          * Gets a value indicating whether or not the provider is ready for use.
//          * @memberof HeatmapImageryProvider.prototype
//          * @type {Boolean}
//          * @readonly
//          */
//         ready : {
//             get : function() {
//                 return this._ready;
//             }
//         },

//         /**
//          * Gets the credit to display when this imagery provider is active.  Typically this is used to credit
//          * the source of the imagery.  This function should not be called before {@link HeatmapImageryProvider#ready} returns true.
//          * @memberof HeatmapImageryProvider.prototype
//          * @type {Credit}
//          * @readonly
//          */
//         credit : {
//             get : function() {
//                 return this._credit;
//             }
//         },

//         /**
//          * Gets a value indicating whether or not the images provided by this imagery provider
//          * include an alpha channel.  If this property is false, an alpha channel, if present, will
//          * be ignored.  If this property is true, any images without an alpha channel will be treated
//          * as if their alpha is 1.0 everywhere.  When this property is false, memory usage
//          * and texture upload time are reduced.
//          * @memberof HeatmapImageryProvider.prototype
//          * @type {Boolean}
//          * @readonly
//          */
//         hasAlphaChannel : {
//             get : function() {
//                 return true;
//             }
//         }
//     });

//     HeatmapImageryProvider.prototype._setWidthAndHeight = function(mbb) {
//         var maxCanvasSize = 2000;
//         var minCanvasSize = 700;
//         this.width = ((mbb.east > 0 && mbb.west < 0) ? mbb.east + Math.abs(mbb.west) : Math.abs(mbb.east - mbb.west));
//         this.height = ((mbb.north > 0 && mbb.south < 0) ? mbb.north + Math.abs(mbb.south) : Math.abs(mbb.north - mbb.south));
//         this._factor = 1;

//         if (this.width > this.height && this.width > maxCanvasSize) {
//             this._factor = this.width / maxCanvasSize;

//             if (this.height / this._factor < minCanvasSize) {
//                 this._factor = this.height / minCanvasSize;
//             }
//         } else if (this.height > this.width && this.height > maxCanvasSize) {
//             this._factor = this.height / maxCanvasSize;

//             if (this.width / this._factor < minCanvasSize) {
//                 this._factor = this.width / minCanvasSize;
//             }
//         } else if (this.width < this.height && this.width < minCanvasSize) {
//             this._factor = this.width / minCanvasSize;

//             if (this.height / this._factor > maxCanvasSize) {
//                 this._factor = this.height / maxCanvasSize;
//             }
//         } else if (this.height < this.width && this.height < minCanvasSize) {
//             this._factor = this.height / minCanvasSize;

//             if (this.width / this._factor > maxCanvasSize) {
//                 this._factor = this.width / maxCanvasSize;
//             }
//         }

//         this.width = this.width / this._factor;
//         this.height = this.height / this._factor;
//     };

//     HeatmapImageryProvider.prototype._getContainer = function(width, height, id) {
//         var c = document.createElement("div");
//         if (id) { c.setAttribute("id", id); }
//         c.setAttribute("style", "width: " + width + "px; height: " + height + "px; margin: 0px; display: none;");
//         document.body.appendChild(c);
//         return c;
//     };

//     /**
//      * Convert a WGS84 location into a Mercator location.
//      *
//      * @param {Object} point The WGS84 location.
//      * @param {Number} [point.x] The longitude of the location.
//      * @param {Number} [point.y] The latitude of the location.
//      * @returns {Cesium.Cartesian3} The Mercator location.
//      */
//     HeatmapImageryProvider.prototype.wgs84ToMercator = function(point) {
//         return this._wmp.project(Cesium.Cartographic.fromDegrees(point.x, point.y));
//     };

//     /**
//      * Convert a WGS84 bounding box into a Mercator bounding box.
//      *
//      * @param {Object} bounds The WGS84 bounding box.
//      * @param {Number} [bounds.north] The northernmost position.
//      * @param {Number} [bounds.south] The southrnmost position.
//      * @param {Number} [bounds.east] The easternmost position.
//      * @param {Number} [bounds.west] The westernmost position.
//      * @returns {Object} The Mercator bounding box containing north, south, east and west properties.
//      */
//     HeatmapImageryProvider.prototype.wgs84ToMercatorBB = function(bounds) {
//         var ne = this._wmp.project(Cesium.Cartographic.fromDegrees(bounds.east, bounds.north));
//         var sw = this._wmp.project(Cesium.Cartographic.fromDegrees(bounds.west, bounds.south));
//         return {
//             north: ne.y,
//             south: sw.y,
//             east: ne.x,
//             west: sw.x
//         };
//     };

//     /**
//      * Convert a mercator location into a WGS84 location.
//      *
//      * @param {Object} point The Mercator lcation.
//      * @param {Number} [point.x] The x of the location.
//      * @param {Number} [point.y] The y of the location.
//      * @returns {Object} The WGS84 location.
//      */
//     HeatmapImageryProvider.prototype.mercatorToWgs84 = function(p) {
//         var wp = this._wmp.unproject(new Cesium.Cartesian3(p.x, p.y));
//         return {
//             x: wp.longitude,
//             y: wp.latitude
//         };
//     };

//     /**
//      * Convert a Mercator bounding box into a WGS84 bounding box.
//      *
//      * @param {Object} bounds The Mercator bounding box.
//      * @param {Number} [bounds.north] The northernmost position.
//      * @param {Number} [bounds.south] The southrnmost position.
//      * @param {Number} [bounds.east] The easternmost position.
//      * @param {Number} [bounds.west] The westernmost position.
//      * @returns {Object} The WGS84 bounding box containing north, south, east and west properties.
//      */
//     HeatmapImageryProvider.prototype.mercatorToWgs84BB = function(bounds) {
//         var sw = this._wmp.unproject(new Cesium.Cartesian3(bounds.west, bounds.south));
//         var ne = this._wmp.unproject(new Cesium.Cartesian3(bounds.east, bounds.north));
//         return {
//             north: this.rad2deg(ne.latitude),
//             east: this.rad2deg(ne.longitude),
//             south: this.rad2deg(sw.latitude),
//             west: this.rad2deg(sw.longitude)
//         };
//     };

//     /**
//      * Convert degrees into radians.
//      *
//      * @param {Number} degrees The degrees to be converted to radians.
//      * @returns {Number} The converted radians.
//      */
//     HeatmapImageryProvider.prototype.deg2rad = function(degrees) {
//         return (degrees * (Math.PI / 180.0));
//     };

//     /**
//      * Convert radians into degrees.
//      *
//      * @param {Number} radians The radians to be converted to degrees.
//      * @returns {Number} The converted degrees.
//      */
//     HeatmapImageryProvider.prototype.rad2deg = function(radians) {
//         return (radians / (Math.PI / 180.0));
//     };

//     /**
//      * Convert a WGS84 location to the corresponding heatmap location.
//      *
//      * @param {Object} point The WGS84 location.
//      * @param {Number} [point.x] The longitude of the location.
//      * @param {Number} [point.y] The latitude of the location.
//      * @returns {Object} The corresponding heatmap location.
//      */
//     HeatmapImageryProvider.prototype.wgs84PointToHeatmapPoint = function(point) {
//         return this.mercatorPointToHeatmapPoint(this.wgs84ToMercator(point));
//     };

//     /**
//      * Convert a mercator location to the corresponding heatmap location.
//      *
//      * @param {Object} point The Mercator lcation.
//      * @param {Number} [point.x] The x of the location.
//      * @param {Number} [point.y] The y of the location.
//      * @returns {Object} The corresponding heatmap location.
//      */
//     HeatmapImageryProvider.prototype.mercatorPointToHeatmapPoint = function(point) {
//         var pn = {};

//         pn.x = Math.round((point.x - this._xoffset) / this._factor + this._spacing);
//         pn.y = Math.round((point.y - this._yoffset) / this._factor + this._spacing);
//         pn.y = this.height - pn.y;

//         return pn;
//     };

//     /**
//      * Set an array of heatmap locations.
//      *
//      * @param {Number} min The minimum allowed value for the data points.
//      * @param {Number} max The maximum allowed value for the data points.
//      * @param {Array} data An array of data points with heatmap coordinates(x, y) and value
//      * @returns {Boolean} Wheter or not the data was successfully added or failed.
//      */
//     HeatmapImageryProvider.prototype.setData = function(min, max, data) {
//         if (data && data.length > 0 && min !== null && min !== false && max !== null && max !== false) {
//             this._heatmap.setData({
//                 min: min,
//                 max: max,
//                 data: data
//             });

//             return true;
//         }

//         return false;
//     };

//     /**
//      * Set an array of WGS84 locations.
//      *
//      * @param {Number} min The minimum allowed value for the data points.
//      * @param {Number} max The maximum allowed value for the data points.
//      * @param {Array} data An array of data points with WGS84 coordinates(x=lon, y=lat) and value
//      * @returns {Boolean} Wheter or not the data was successfully added or failed.
//      */
//     HeatmapImageryProvider.prototype.setWGS84Data = function(min, max, data) {
//         if (data && data.length > 0 && min !== null && min !== false && max !== null && max !== false) {
//             var convdata = [];

//             for (var i = 0; i < data.length; i++) {
//                 var gp = data[i];

//                 var hp = this.wgs84PointToHeatmapPoint(gp);
//                 if (gp.value || gp.value === 0) { hp.value = gp.value; }

//                 convdata.push(hp);
//             }

//             return this.setData(min, max, convdata);
//         }

//         return false;
//     };

//     /**
//      * Gets the credits to be displayed when a given tile is displayed.
//      *
//      * @param {Number} x The tile X coordinate.
//      * @param {Number} y The tile Y coordinate.
//      * @param {Number} level The tile level;
//      * @returns {Credit[]} The credits to be displayed when the tile is displayed.
//      *
//      * @exception {DeveloperError} <code>getTileCredits</code> must not be called before the imagery provider is ready.
//      */
//     HeatmapImageryProvider.prototype.getTileCredits = function(x, y, level) {
//         return undefined;
//     };

//     /**
//      * Requests the image for a given tile.  This function should
//      * not be called before {@link HeatmapImageryProvider#ready} returns true.
//      *
//      * @param {Number} x The tile X coordinate.
//      * @param {Number} y The tile Y coordinate.
//      * @param {Number} level The tile level.
//      * @returns {Promise} A promise for the image that will resolve when the image is available, or
//      *          undefined if there are too many active requests to the server, and the request
//      *          should be retried later.  The resolved image may be either an
//      *          Image or a Canvas DOM object.
//      *
//      * @exception {DeveloperError} <code>requestImage</code> must not be called before the imagery provider is ready.
//      */
//     HeatmapImageryProvider.prototype.requestImage = function(x, y, level) {
//         if (!this._ready) {
//             throw new DeveloperError('requestImage must not be called before the imagery provider is ready.');
//         }

//         return this._image;
//     };

//     /**
//      * Picking features is not currently supported by this imagery provider, so this function simply returns
//      * undefined.
//      *
//      * @param {Number} x The tile X coordinate.
//      * @param {Number} y The tile Y coordinate.
//      * @param {Number} level The tile level.
//      * @param {Number} longitude The longitude at which to pick features.
//      * @param {Number} latitude  The latitude at which to pick features.
//      * @return {Promise} A promise for the picked features that will resolve when the asynchronous
//      *                   picking completes.  The resolved value is an array of {@link ImageryLayerFeatureInfo}
//      *                   instances.  The array may be empty if no features are found at the given location.
//      *                   It may also be undefined if picking is not supported.
//      */
//     HeatmapImageryProvider.prototype.pickFeatures = function() {
//         return undefined;
//     };

//     return HeatmapImageryProvider;
// });

/*  DON'T TOUCH:
 *
 *  heatmap.js v2.0.0 | JavaScript Heatmap Library: http://www.patrick-wied.at/static/heatmapjs/
 *
 *  Copyright 2008-2014 Patrick Wied <heatmapjs@patrick-wied.at> - All rights reserved.
 *  Dual licensed under MIT and Beerware license 
 *
 *  :: 2014-10-31 21:16
 */
(function(a, b, c) { if (typeof module !== "undefined" && module.exports) { module.exports = c() } else if (typeof define === "function" && define.amd) { define(c) } else { b[a] = c() } })("h337", this, function() { var a = { defaultRadius: 40, defaultRenderer: "canvas2d", defaultGradient: { .25: "rgb(0,0,255)", .55: "rgb(0,255,0)", .85: "yellow", 1: "rgb(255,0,0)" }, defaultMaxOpacity: 1, defaultMinOpacity: 0, defaultBlur: .85, defaultXField: "x", defaultYField: "y", defaultValueField: "value", plugins: {} }; var b = function h() { var b = function d(a) { this._coordinator = {};
            this._data = [];
            this._radi = [];
            this._min = 0;
            this._max = 1;
            this._xField = a["xField"] || a.defaultXField;
            this._yField = a["yField"] || a.defaultYField;
            this._valueField = a["valueField"] || a.defaultValueField; if (a["radius"]) { this._cfgRadius = a["radius"] } }; var c = a.defaultRadius;
        b.prototype = { _organiseData: function(a, b) { var d = a[this._xField]; var e = a[this._yField]; var f = this._radi; var g = this._data; var h = this._max; var i = this._min; var j = a[this._valueField] || 1; var k = a.radius || this._cfgRadius || c; if (!g[d]) { g[d] = [];
                    f[d] = [] } if (!g[d][e]) { g[d][e] = j;
                    f[d][e] = k } else { g[d][e] += j } if (g[d][e] > h) { if (!b) { this._max = g[d][e] } else { this.setDataMax(g[d][e]) } return false } else { return { x: d, y: e, value: j, radius: k, min: i, max: h } } }, _unOrganizeData: function() { var a = []; var b = this._data; var c = this._radi; for (var d in b) { for (var e in b[d]) { a.push({ x: d, y: e, radius: c[d][e], value: b[d][e] }) } } return { min: this._min, max: this._max, data: a } }, _onExtremaChange: function() { this._coordinator.emit("extremachange", { min: this._min, max: this._max }) }, addData: function() { if (arguments[0].length > 0) { var a = arguments[0]; var b = a.length; while (b--) { this.addData.call(this, a[b]) } } else { var c = this._organiseData(arguments[0], true); if (c) { this._coordinator.emit("renderpartial", { min: this._min, max: this._max, data: [c] }) } } return this }, setData: function(a) { var b = a.data; var c = b.length;
                this._data = [];
                this._radi = []; for (var d = 0; d < c; d++) { this._organiseData(b[d], false) }
                this._max = a.max;
                this._min = a.min || 0;
                this._onExtremaChange();
                this._coordinator.emit("renderall", this._getInternalData()); return this }, removeData: function() {}, setDataMax: function(a) { this._max = a;
                this._onExtremaChange();
                this._coordinator.emit("renderall", this._getInternalData()); return this }, setDataMin: function(a) { this._min = a;
                this._onExtremaChange();
                this._coordinator.emit("renderall", this._getInternalData()); return this }, setCoordinator: function(a) { this._coordinator = a }, _getInternalData: function() { return { max: this._max, min: this._min, data: this._data, radi: this._radi } }, getData: function() { return this._unOrganizeData() } }; return b }(); var c = function i() { var a = function(a) { var b = a.gradient || a.defaultGradient; var c = document.createElement("canvas"); var d = c.getContext("2d");
            c.width = 256;
            c.height = 1; var e = d.createLinearGradient(0, 0, 256, 1); for (var f in b) { e.addColorStop(f, b[f]) }
            d.fillStyle = e;
            d.fillRect(0, 0, 256, 1); return d.getImageData(0, 0, 256, 1).data }; var b = function(a, b) { var c = document.createElement("canvas"); var d = c.getContext("2d"); var e = a; var f = a;
            c.width = c.height = a * 2; if (b == 1) { d.beginPath();
                d.arc(e, f, a, 0, 2 * Math.PI, false);
                d.fillStyle = "rgba(0,0,0,1)";
                d.fill() } else { var g = d.createRadialGradient(e, f, a * b, e, f, a);
                g.addColorStop(0, "rgba(0,0,0,1)");
                g.addColorStop(1, "rgba(0,0,0,0)");
                d.fillStyle = g;
                d.fillRect(0, 0, 2 * a, 2 * a) } return c }; var c = function(a) { var b = []; var c = a.min; var d = a.max; var e = a.radi; var a = a.data; var f = Object.keys(a); var g = f.length; while (g--) { var h = f[g]; var i = Object.keys(a[h]); var j = i.length; while (j--) { var k = i[j]; var l = a[h][k]; var m = e[h][k];
                    b.push({ x: h, y: k, value: l, radius: m }) } } return { min: c, max: d, data: b } };

        function d(b) { var c = b.container; var d = this.shadowCanvas = document.createElement("canvas"); var e = this.canvas = b.canvas || document.createElement("canvas"); var f = this._renderBoundaries = [1e4, 1e4, 0, 0]; var g = getComputedStyle(b.container) || {};
            e.className = "heatmap-canvas";
            this._width = e.width = d.width = +g.width.replace(/px/, "");
            this._height = e.height = d.height = +g.height.replace(/px/, "");
            this.shadowCtx = d.getContext("2d");
            this.ctx = e.getContext("2d");
            e.style.cssText = d.style.cssText = "position:absolute;left:0;top:0;";
            c.style.position = "relative";
            c.appendChild(e);
            this._palette = a(b);
            this._templates = {};
            this._setStyles(b) }
        d.prototype = { renderPartial: function(a) { this._drawAlpha(a);
                this._colorize() }, renderAll: function(a) { this._clear();
                this._drawAlpha(c(a));
                this._colorize() }, _updateGradient: function(b) { this._palette = a(b) }, updateConfig: function(a) { if (a["gradient"]) { this._updateGradient(a) }
                this._setStyles(a) }, setDimensions: function(a, b) { this._width = a;
                this._height = b;
                this.canvas.width = this.shadowCanvas.width = a;
                this.canvas.height = this.shadowCanvas.height = b }, _clear: function() { this.shadowCtx.clearRect(0, 0, this._width, this._height);
                this.ctx.clearRect(0, 0, this._width, this._height) }, _setStyles: function(a) { this._blur = a.blur == 0 ? 0 : a.blur || a.defaultBlur; if (a.backgroundColor) { this.canvas.style.backgroundColor = a.backgroundColor }
                this._opacity = (a.opacity || 0) * 255;
                this._maxOpacity = (a.maxOpacity || a.defaultMaxOpacity) * 255;
                this._minOpacity = (a.minOpacity || a.defaultMinOpacity) * 255;
                this._useGradientOpacity = !!a.useGradientOpacity }, _drawAlpha: function(a) { var c = this._min = a.min; var d = this._max = a.max; var a = a.data || []; var e = a.length; var f = 1 - this._blur; while (e--) { var g = a[e]; var h = g.x; var i = g.y; var j = g.radius; var k = Math.min(g.value, d); var l = h - j; var m = i - j; var n = this.shadowCtx; var o; if (!this._templates[j]) { this._templates[j] = o = b(j, f) } else { o = this._templates[j] }
                    n.globalAlpha = (k - c) / (d - c);
                    n.drawImage(o, l, m); if (l < this._renderBoundaries[0]) { this._renderBoundaries[0] = l } if (m < this._renderBoundaries[1]) { this._renderBoundaries[1] = m } if (l + 2 * j > this._renderBoundaries[2]) { this._renderBoundaries[2] = l + 2 * j } if (m + 2 * j > this._renderBoundaries[3]) { this._renderBoundaries[3] = m + 2 * j } } }, _colorize: function() { var a = this._renderBoundaries[0]; var b = this._renderBoundaries[1]; var c = this._renderBoundaries[2] - a; var d = this._renderBoundaries[3] - b; var e = this._width; var f = this._height; var g = this._opacity; var h = this._maxOpacity; var i = this._minOpacity; var j = this._useGradientOpacity; if (a < 0) { a = 0 } if (b < 0) { b = 0 } if (a + c > e) { c = e - a } if (b + d > f) { d = f - b } var k = this.shadowCtx.getImageData(a, b, c, d); var l = k.data; var m = l.length; var n = this._palette; for (var o = 3; o < m; o += 4) { var p = l[o]; var q = p * 4; if (!q) { continue } var r; if (g > 0) { r = g } else { if (p < h) { if (p < i) { r = i } else { r = p } } else { r = h } }
                    l[o - 3] = n[q];
                    l[o - 2] = n[q + 1];
                    l[o - 1] = n[q + 2];
                    l[o] = j ? n[q + 3] : r }
                k.data = l;
                this.ctx.putImageData(k, a, b);
                this._renderBoundaries = [1e3, 1e3, 0, 0] }, getValueAt: function(a) { var b; var c = this.shadowCtx; var d = c.getImageData(a.x, a.y, 1, 1); var e = d.data[3]; var f = this._max; var g = this._min;
                b = Math.abs(f - g) * (e / 255) >> 0; return b }, getDataURL: function() { return this.canvas.toDataURL() } }; return d }(); var d = function j() { var b = false; if (a["defaultRenderer"] === "canvas2d") { b = c } return b }(); var e = { merge: function() { var a = {}; var b = arguments.length; for (var c = 0; c < b; c++) { var d = arguments[c]; for (var e in d) { a[e] = d[e] } } return a } }; var f = function k() { var c = function h() {
            function a() { this.cStore = {} }
            a.prototype = { on: function(a, b, c) { var d = this.cStore; if (!d[a]) { d[a] = [] }
                    d[a].push(function(a) { return b.call(c, a) }) }, emit: function(a, b) { var c = this.cStore; if (c[a]) { var d = c[a].length; for (var e = 0; e < d; e++) { var f = c[a][e];
                            f(b) } } } }; return a }(); var f = function(a) { var b = a._renderer; var c = a._coordinator; var d = a._store;
            c.on("renderpartial", b.renderPartial, b);
            c.on("renderall", b.renderAll, b);
            c.on("extremachange", function(b) { a._config.onExtremaChange && a._config.onExtremaChange({ min: b.min, max: b.max, gradient: a._config["gradient"] || a._config["defaultGradient"] }) });
            d.setCoordinator(c) };

        function g() { var g = this._config = e.merge(a, arguments[0] || {});
            this._coordinator = new c; if (g["plugin"]) { var h = g["plugin"]; if (!a.plugins[h]) { throw new Error("Plugin '" + h + "' not found. Maybe it was not registered.") } else { var i = a.plugins[h];
                    this._renderer = new i.renderer(g);
                    this._store = new i.store(g) } } else { this._renderer = new d(g);
                this._store = new b(g) }
            f(this) }
        g.prototype = { addData: function() { this._store.addData.apply(this._store, arguments); return this }, removeData: function() { this._store.removeData && this._store.removeData.apply(this._store, arguments); return this }, setData: function() { this._store.setData.apply(this._store, arguments); return this }, setDataMax: function() { this._store.setDataMax.apply(this._store, arguments); return this }, setDataMin: function() { this._store.setDataMin.apply(this._store, arguments); return this }, configure: function(a) { this._config = e.merge(this._config, a);
                this._renderer.updateConfig(this._config);
                this._coordinator.emit("renderall", this._store._getInternalData()); return this }, repaint: function() { this._coordinator.emit("renderall", this._store._getInternalData()); return this }, getData: function() { return this._store.getData() }, getDataURL: function() { return this._renderer.getDataURL() }, getValueAt: function(a) { if (this._store.getValueAt) { return this._store.getValueAt(a) } else if (this._renderer.getValueAt) { return this._renderer.getValueAt(a) } else { return null } } }; return g }(); var g = { create: function(a) { return new f(a) }, register: function(b, c) { a.plugins[b] = c } }; return g });;
///<jscompress sourcefile="VFGImgProvider.js" />
VFG.Provider=function(){}
VFG.Provider.Map=new Map();
VFG.Provider.hasTerrain=false;
VFG.Provider.createUrlTemplateImageryProvider = function (ops) {
	return new Cesium.UrlTemplateImageryProvider(ops);
};

/**
 * WebMapTile
 * @param {Object} ops
 */
VFG.Provider.createWebMapTileServiceImageryProvider = function (ops) {
	return new Cesium.WebMapTileServiceImageryProvider(ops);
};

/**
 * BingMaps
 * @param {Object} ops
 */
VFG.Provider.createBingMapsImageryProvider = function (ops) {
	return new Cesium.BingMapsImageryProvider(ops);
};

/**
 * BingMapsGeocoderService
 * @param {Object} ops
 */
VFG.Provider.createBingMapsGeocoderService = function (ops) {
	return new Cesium.BingMapsGeocoderService(ops);
};

/**
 * ArcGisMap
 * @param {Object} ops
 */
VFG.Provider.createArcGisMapServerImageryProvider = function (ops) {
	return new Cesium.ArcGisMapServerImageryProvider(ops);
};

/**
 * ArcGISTiledElevationTerrain
 * @param {Object} ops
 */
VFG.Provider.createArcGISTiledElevationTerrainProvider = function (ops) {
	return new Cesium.ArcGISTiledElevationTerrainProvider(ops);
};

/**
 * OpenStreetMapImageryProvider
 * @param {Object} ops
 */
VFG.Provider.createOpenStreetMapImageryProvider = function (ops) {
	return new Cesium.OpenStreetMapImageryProvider(ops);
};

/**
 * SingleTileImageryProvider
 * @param {Object} ops
 */
VFG.Provider.createSingleTileImageryProvider = function (ops) {
	return new Cesium.SingleTileImageryProvider(ops);
};

/**
 * TileMapServiceImageryProvider
 * @param {Object} ops
 */
VFG.Provider.createTileMapServiceImageryProvider = function (ops) {
	return new Cesium.TileMapServiceImageryProvider(ops);
};

/**
 * WebMapServiceImageryProvider
 * @param {Object} ops
 */
VFG.Provider.createWebMapServiceImageryProvider = function (ops) {
	return new Cesium.WebMapServiceImageryProvider(ops);
};

/**
 * CesiumTerrainProvider
 * @param {Object} ops
 */
VFG.Provider.createTerrainProvider = function (ops) {
	return new Cesium.CesiumTerrainProvider(ops);
};

/**
 * 官网世界地形
 */
VFG.Provider.createWorldTerrainProvider = function () {
	return new Cesium.createWorldTerrain();
};


/**
 * 获取图层集合
 */
VFG.Provider.getImageryLayers  = function (viewer) {
	return viewer.imageryLayers;
};


/**
 * 是否包含影像
 * @param {Object} layer
 */
VFG.Provider.containsImageryProvider  = function (viewer,layer) {
	 return viewer.imageryLayers.contains(layer);
};

/**
 * 序号获取影像
 * @param {Object} index
 */
VFG.Provider.getImageryProvider  = function (viewer,index) {
	 return viewer.imageryLayers.get(layer);
};

/**
 * 获取图层索引
 * @param {Object} layer
 */
VFG.Provider.indexOfImageryProvider  = function (viewer,layer) {
	 return viewer.imageryLayers.indexOf(layer);
};

/**
 * 清空图层
 * @param {Object} destroy
 */
VFG.Provider.removeAllImageryProviders  = function (viewer,destroy) {
	 return viewer.imageryLayers.removeAll(destroy);
};



/**
 * 至顶
 * @param {Object} layer
 */
VFG.Provider.raiseToTopImageryProviders  = function (viewer,layer) {
	 return viewer.imageryLayers.raiseToTop(layer);
};

/**
 * 上移
 * @param {Object} layer
 */
VFG.Provider.raiseImageryProviders  = function (viewer,layer) {
	 return viewer.imageryLayers.raise(layer);
};

/**
 * 下移
 * @param {Object} layer
 */
VFG.Provider.lowerImageryProviders  = function (viewer,layer) {
	 return viewer.imageryLayers.lower(layer);
};

/**
 * 至底
 * @param {Object} layer
 */
VFG.Provider.lowerToBottomImageryProviders  = function (viewer,layer) {
	 return viewer.imageryLayers.lowerToBottom(layer);
};

/**
 * 获取地形集合
 * @param {Object} ops
 * @param {Object} index
 */
VFG.Provider.getTerrainLayers  = function (viewer) {
	 return viewer.terrainLayers;
};

/**
 * 设置地形
 * @param {Object} terrainLayer
 */
VFG.Provider.addTerrainProvider  = function (viewer,terrainLayer) {
	 viewer.terrainProvider=terrainLayer;
};

/**
 * 移除地形
 * @param {Object} terrainLayer
 */
VFG.Provider.removeTerrainProvider  = function (viewer,terrainLayer) {
   viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider({});
};

VFG.Provider.removeTerrainProvider  = function (viewer,terrainLayer) {
	viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider({});
};


/**
 * 添加图层
 * @param {Object} ops
 */
VFG.Provider.addImageryProvider  = function (viewer,ops) {
	viewer.imageryLayers.addImageryProvider(ops);
};



VFG.Provider.addImageryProvider  = function (viewer,ops,index) {
	 viewer.imageryLayers.addImageryProvider(ops,index);
};

/**
 * 解析添加
 */
VFG.Provider.addImageryProvidersFromServ  = function (viewer,imglayers) {
	for(var i=0;i<imglayers.length;i++){
		var imglayer=imglayers[i];
		if(!this.Map.has(imglayer.id) && imglayer.show=='1'){
			if('terrain'==imglayer.dataType  ){
				var terrainProvider=VFG.Provider.getTerrainProviderFromServ(imglayer);
				if(terrainProvider){
					 this.hasTerrain=true;
					viewer.terrainProvider=terrainProvider;
					this.Map.set(imglayer.id,terrainProvider);
				}
			}else{
				var imageryProvider=this.getImageryProviderFromServ(imglayer);
				if(imageryProvider){
					var sImgPro=viewer.imageryLayers.addImageryProvider(imageryProvider);
					this.Map.set(imglayer.id,sImgPro);
				}
			}

		}
	}
};

VFG.Provider.packProvider= function (imglayer) {
	if('terrain'==imglayer.dataType){
		return this.getTerrainProviderFromServ(imglayer);
	}else{
		return this.getImageryProviderFromServ(imglayer);
	}
};

VFG.Provider.addImageryProviderFromServ  = function (viewer,imglayer) {
	if(!this.Map.has(imglayer.id)){
		var imageryProvider=this.getImageryProviderFromServ(imglayer);
		if(imageryProvider){
			var sImgPro=viewer.imageryLayers.addImageryProvider(imageryProvider);
			this.Map.set(imglayer.id,sImgPro);
		}
	}
};

VFG.Provider.getImageryProviderFromServ  = function (imglayer) {
	if(imglayer.parameters){
		var parameter=eval('(' + imglayer.parameters + ')') ;
		if(parameter){
			if('URL'==imglayer.serverType){
				return this.createUrlTemplateImageryProvider(parameter);
			}
			else if('WMS'==imglayer.serverType){
				return new Cesium.WebMapServiceImageryProvider(parameter);
			}
			else if('WMTS'==imglayer.serverType){
				return new Cesium.WebMapTileServiceImageryProvider(parameter);
			}
			else if('ArcGis'==imglayer.serverType){
				return new Cesium.ArcGisMapServerImageryProvider(parameter);
			}
		}
	}
};

/**
 * 地形数据
 */
VFG.Provider.getTerrainProviderFromServ  = function (imglayer) {
	if(imglayer.parameters){
		var parameter=eval('(' + imglayer.parameters + ')') ;
		if(parameter){
			this.hasTerrain=true;
			return new Cesium.CesiumTerrainProvider(parameter)
		}
	}
};

/**
 * 移除图层
 * @param {Object} layer
 * @param {Object} destroy
 */
VFG.Provider.removeImageryProviders  = function (viewer,layer, destroy) {
	 return viewer.imageryLayers.remove(layer,destroy);
};

/**
 * 根据ID删除图层
 */
VFG.Provider.removeById  = function (viewer,id) {
	if(this.Map.has(id)){
		 viewer.imageryLayers.remove(this.Map.get(id),true);
		 this.Map.delete(id);
	}
};
VFG.Provider.removeTerrainProviderById  = function (viewer,id) {
	if(this.Map.has(id)){
		viewer.terrainProvider=new Cesium.EllipsoidTerrainProvider({});;
		 this.Map.delete(id);
		 this.hasTerrain=false;
	}
};


;
///<jscompress sourcefile="VFGUtil.js" />
VFG.Util=function(){
}
//存放容器
VFG.Util.primitiveMap = new Map();

VFG.Util.getUuid = function() {
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4"; 
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); 
	s[8] = s[13] = s[18] = s[23] = "-";
	var uuid = s.join("");
	return uuid;
};



/**
 * 删除数组
 * index：数组中需要删除数据的起始位置；n：需要删除的元素，数据的个数。
 */
VFG.Util.splice = function(arr,index, n) {
	if(arr){
		arr.splice(index, n);
	}
	return arr;
};
/**
 * 插入
 */
VFG.Util.inset = function(arr,index,data) {
	if(arr){
		arr.splice(index,0,data);
	}
	return arr;
};

/**
 * 替换
 */
VFG.Util.replace = function(arr,n,data) {
	if(arr){
		arr.splice(index,n,data);
	}
	return arr;
};

/**
 * 场景截图
 */
VFG.Util.getSceneImg = function (viewer,width,height) {
	var canvas = viewer.scene.canvas;
    var imageWidth = width?width:800;
    var img = Canvas2Image.convertToImage(canvas, imageWidth, height?height:imageWidth * canvas.height / canvas.width,'png');
    return img.src
}

/**
 * 获取视角
 */
VFG.Util.getVisualAngle=function(viewer) {
	return {
		heading:viewer.camera.heading,
		pitch:viewer.camera.pitch,
		roll:viewer.camera.roll,
		position:viewer.camera.position
	}
};

VFG.Util.removeEntityById=function(viewer,uniqueId) {
	viewer.entities.removeById(uniqueId);
};

VFG.Util.getEntityById=function(viewer,uniqueId) {
	return viewer.entities.getById(uniqueId);
};

VFG.Util.getEntityById=function(viewer,uniqueId) {
	return viewer.entities.getById(uniqueId);
};

VFG.Util.getCenterPoint= function(cartesianA,cartesianB) {
	var _self = this;
	let AtoB = Cesium.Cartesian3.subtract(cartesianA, cartesianB, new Cesium.Cartesian3());
	let cartesian4_1 = Cesium.Cartesian3.divideByScalar(AtoB, 2, new Cesium.Cartesian3())
	let cartesianC= Cesium.Cartesian3.add(cartesian4_1, cartesianB, new Cesium.Cartesian3());
    return cartesianC;
}

/**
 * 经纬度获取屏幕坐标
 */
VFG.Util.getC2FormLnLa = function(viewer,position) {
	return Cesium.SceneTransforms.wgs84ToWindowCoordinates(viewer.scene,this.getC3FormLnLa(position))
}


/**
 * 经纬度转笛卡尔坐标
 * position:{
 * 	x:经度
 *  y:维度
 *  z:高度
 * }
 */
VFG.Util.getC3FormLnLa = function(position) {
	return Cesium.Cartesian3.fromDegrees(position.x*1,position.y*1,position.z*1);
}

/**
 * 笛卡尔坐标转经纬度
 */
VFG.Util.getLnLaFormC3 = function(viewer,cartesian3) {
	var ellipsoid=viewer.scene.globe.ellipsoid;
	var cartographic=ellipsoid.cartesianToCartographic(cartesian3);
	var lat=Cesium.Math.toDegrees(cartographic.latitude).toFixed(7);
	var lng=Cesium.Math.toDegrees(cartographic.longitude).toFixed(7);
	var alt=cartographic.height.toFixed(2);
	return {
		x:lng,
		y:lat,
		z:alt
	};
}

//
///**
// * 获取鼠标当前的屏幕坐标位置的三维Cesium坐标
// * @param {Cesium.Scene} scene 
// * @param {Cesium.Cartesian2} position 二维屏幕坐标位置
// * @param {Cesium.Entity} noPickEntity 排除的对象（主要用于绘制中，排除对自己本身的拾取）
// */
VFG.Util.getScreenToC3=function(viewer, position, noPickEntity) {
	var scene = viewer.scene;
	var cartesian3;
	if (scene.mode !== Cesium.SceneMode.MORPHING) {
		var pickedObject = scene.pick(position);
		if (scene.pickPositionSupported && Cesium.defined(pickedObject)) {
			if(!this.hasPickedModel(pickedObject,noPickEntity)){
				cartesian3 = viewer.scene.pickPosition(position);
				if (Cesium.defined(cartesian3)) {
				    var height = Cesium.Cartographic.fromCartesian(cartesian3).height;
				    var lat = Cesium.Math.toDegrees(Cesium.Cartographic.fromCartesian(cartesian3).latitude);
				    var lng = Cesium.Math.toDegrees(Cesium.Cartographic.fromCartesian(cartesian3).longitude);
				    return viewer.scene.clampToHeight(cartesian3);
	            }
			}
		}
	}
	
	//获取地形表面的经纬度高程坐标：
	if (!Cesium.defined(cartesian3) &&  (viewer.scene)) {
		var ray = viewer.camera.getPickRay(position);
		if (Cesium.defined(ray)) {
			cartesian3 = viewer.scene.globe.pick(ray, viewer.scene);
			if (Cesium.defined(cartesian3)){
			    var height = Cesium.Cartographic.fromCartesian(cartesian3).height;
			    var lat = Cesium.Math.toDegrees(Cesium.Cartographic.fromCartesian(cartesian3).latitude);
			    var lng = Cesium.Math.toDegrees(Cesium.Cartographic.fromCartesian(cartesian3).longitude);
			    return Cesium.Cartesian3.fromDegrees(lng, lat, height>0?height:0);
			}
		}

	}
	
	//二维坐标，获取椭球体表面的经纬度坐标：
	if (!Cesium.defined(cartesian3)) {
		cartesian3 = viewer.scene.camera.pickEllipsoid(position,viewer.scene.globe.ellipsoid);
		return cartesian3;
	}
	return cartesian3;
}



/**

 * 获取鼠标当前的屏幕坐标位置的三维Cesium坐标

 * @param {Cesium.Scene} scene 

 * @param {Cesium.Cartesian2} position 二维屏幕坐标位置

 * @param {Cesium.Entity} noPickEntity 排除的对象（主要用于绘制中，排除对自己本身的拾取）

 */
//VFG.Util.getScreenToC3=function(viewer, position, noPickEntity) {
//	var _this=this;
//	var scene = viewer.scene;
//    var cartesian;
//    //在模型上提取坐标   
//    var pickedObject;
//    try {
//        pickedObject = scene.pick(position, 5, 5);
//    } catch (e) {
//        console.log("scene.pick 拾取位置时异常");
//    }
//
//    if (scene.pickPositionSupported && Cesium.defined(pickedObject)) {
//        cartesian = scene.pickPosition(position);
//        if (Cesium.defined(cartesian)) {
//            var height = Cesium.Cartographic.fromCartesian(cartesian).height;
//            var lat = Cesium.Math.toDegrees(Cesium.Cartographic.fromCartesian(cartesian).latitude);
//            var lng = Cesium.Math.toDegrees(Cesium.Cartographic.fromCartesian(cartesian).longitude);
//            console.log(height);
//            return Cesium.Cartesian3.fromDegrees(lng, lat, height>0?height+1:0);
//        }
//    } else {}
//
//        //超图s3m数据拾取
//    if (Cesium.defined(Cesium.S3MTilesLayer)) {
//        cartesian = scene.pickPosition(position);
//        if (Cesium.defined(cartesian)) {
//            var height = Cesium.Cartographic.fromCartesian(cartesian).height;
//            var lat = Cesium.Math.toDegrees(Cesium.Cartographic.fromCartesian(cartesian).latitude);
//            var lng = Cesium.Math.toDegrees(Cesium.Cartographic.fromCartesian(cartesian).longitude);
//            return Cesium.Cartesian3.fromDegrees(lng, lat, height>0?height+1:0);
//        }
//    }
//
//    //onlyPickModelPosition是在 ViewerEx 中定义的对外属性
//    //通过 viewer.mars.onlyPickModelPosition 进行修改
//    if (scene.onlyPickModelPosition) return cartesian; //只取模型上的时候，不继续读取了
//
//
//    //测试scene.pickPosition和globe.pick的适用场景 https://zhuanlan.zhihu.com/p/44767866
//    //1. globe.pick的结果相对稳定准确，不论地形深度检测开启与否，不论加载的是默认地形还是别的地形数据；
//    //2. scene.pickPosition只有在开启地形深度检测，且不使用默认地形时是准确的。
//    //注意点： 1. globe.pick只能求交地形； 2. scene.pickPosition不仅可以求交地形，还可以求交除地形以外其他所有写深度的物体。
//
//    //提取鼠标点的地理坐标 
//    if (scene.mode === Cesium.SceneMode.SCENE3D) {
//        //三维模式下
//        var pickRay = scene.camera.getPickRay(position);
//        cartesian = scene.globe.pick(pickRay, scene);
//    } else {
//        //二维模式下
//        cartesian = scene.camera.pickEllipsoid(position, scene.globe.ellipsoid);
//    }
//
//    var height = Cesium.Cartographic.fromCartesian(cartesian).height;
//    var lat = Cesium.Math.toDegrees(Cesium.Cartographic.fromCartesian(cartesian).latitude);
//    var lng = Cesium.Math.toDegrees(Cesium.Cartographic.fromCartesian(cartesian).longitude);
//    return Cesium.Cartesian3.fromDegrees(lng, lat, height>0?height+1:0);
//}




/**
 * 模型矩阵转笛卡尔坐标
 */
VFG.Util.modelMatrixToC3=function (modelMatrix){
	var cartesian3=new Cesium.Cartesian3();
	Cesium.Matrix4.getTranslation(modelMatrix,cartesian3);//根据最终变换矩阵m得到p2
	return cartesian3
}

VFG.Util.modelMatrixToRotate=function (modelMatrix){
    var m1 = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Matrix4.getTranslation(modelMatrix, new Cesium.Cartesian3()), Cesium.Ellipsoid.WGS84, new Cesium.Matrix4());
    // 矩阵相除
    var m3 = Cesium.Matrix4.multiply(Cesium.Matrix4.inverse(m1, new Cesium.Matrix4()), modelMatrix, new Cesium.Matrix4());
    // 得到旋转矩阵
    var mat3 = Cesium.Matrix4.getMatrix3(m3, new Cesium.Matrix3());
    // 计算四元数
    var q = Cesium.Quaternion.fromRotationMatrix(mat3);
    // 计算旋转角(弧度)
    var hpr = Cesium.HeadingPitchRoll.fromQuaternion(q);
    // 得到角度
    var heading = Cesium.Math.toDegrees(hpr.heading).toFixed(2)*1;;
    var pitch = Cesium.Math.toDegrees(hpr.pitch).toFixed(2)*1;;
    var roll = Cesium.Math.toDegrees(hpr.roll).toFixed(2)*1;;
    if(heading<0){
    	heading+=360;
    }
    if(pitch<0){
    	pitch+=360;
    }
    if(roll<0){
    	roll+=360;
    }
	return {x:pitch,y:heading,z:roll}
}


VFG.Util.modelMatrixToHeadingPitchRoll=function (modelMatrix){
    var m1 = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Matrix4.getTranslation(modelMatrix, new Cesium.Cartesian3()), Cesium.Ellipsoid.WGS84, new Cesium.Matrix4());
    // 矩阵相除
    var m3 = Cesium.Matrix4.multiply(Cesium.Matrix4.inverse(m1, new Cesium.Matrix4()), modelMatrix, new Cesium.Matrix4());
    // 得到旋转矩阵
    var mat3 = Cesium.Matrix4.getMatrix3(m3, new Cesium.Matrix3());
    // 计算四元数
    var q = Cesium.Quaternion.fromRotationMatrix(mat3);
    // 计算旋转角(弧度)
    var headingPitchRoll = Cesium.HeadingPitchRoll.fromQuaternion(q);
	return headingPitchRoll;
}

/**
 * 判断是否包含本身
 */
VFG.Util.hasPickedModel=function(pickedObject, noPickEntity) {
    if (Cesium.defined(pickedObject.id)) {
        //entity 
        var entity = pickedObject.id;
        if (entity._noMousePosition) return entity; //排除标识不拾取的对象
        if (noPickEntity && entity == noPickEntity) return entity;
    }

    if (Cesium.defined(pickedObject.primitive)) {
        var primitive = pickedObject.primitive;
        if (primitive._noMousePosition) return primitive; //排除标识不拾取的对象
        if (noPickEntity && primitive == noPickEntity) return primitive;
    }
    return null;
}

VFG.Util.getScreenToLnLa  = function(viewer, position,noPickEntity) {
	var cartesian3=VFG.Util.getScreenToC3(viewer, position, noPickEntity);
	if(Cesium.defined(cartesian3)){
		return VFG.Util.getLnLaFormC3(viewer,cartesian3);
	}
	return null;
}

/**
 * 经纬度转笛卡尔坐标
 */
VFG.Util.getC3ToLnLa  = function(viewer, cartesian3) {
	var ellipsoid=viewer.scene.globe.ellipsoid;
	var cartographic=ellipsoid.cartesianToCartographic(cartesian3);
	var lat=Cesium.Math.toDegrees(cartographic.latitude);
	var lng=Cesium.Math.toDegrees(cartographic.longitude);
	var height=cartographic.height;
	return {x:lng,y:lat,z:height};
}

/**
 * 屏幕坐标
 */
VFG.Util.getCartesian2 = function(x,y) {
	var _this=this;
	if(Cesium.defined(x) && Cesium.defined(y) ){
		return new Cesium.Cartesian2(x*1,y*1)
	}
	return null;
};

/**
 * 笛卡尔坐标
 */
VFG.Util.getCartesian3 = function(x,y,z) {
	var _this=this;
	if(Cesium.defined(x) && Cesium.defined(y) && Cesium.defined(z)){
		return new Cesium.Cartesian3(x*1,y*1,z*1)
	}
	return null;
};

VFG.Util.getDistanceDisplayCondition = function(x,y) {
	var _this=this;
	if(Cesium.defined(x) && Cesium.defined(y) ){
		return new Cesium.DistanceDisplayCondition(x*1,y*1)
	}
	return null;
};
VFG.Util.getNearFarScalar = function(near, nearValue, far, farValue) {
	var _this=this;
	if(Cesium.defined(near) && Cesium.defined(nearValue) && Cesium.defined(far) && Cesium.defined(farValue)){
		return new Cesium.NearFarScalar(near*1, nearValue*1, far*1, farValue*1);
	}
	return null;
};

VFG.Util.getHorizontalOrigin = function(value){
	if("0"===value){
		return  Cesium.HorizontalOrigin.CENTER ;
	}
	else if("1"===value){
		return  Cesium.HorizontalOrigin.LEFT  ;
	}
	else if("2"===value){
		return  Cesium.HorizontalOrigin.RIGHT  ;
	}
	else{
		return  Cesium.HorizontalOrigin.CENTER;
	}
} 
VFG.Util.getHeightReference = function(value){
	if("0"===value){
		return  Cesium.HeightReference.NONE ;
	}
	else if("1"===value){
		return  Cesium.HeightReference.CLAMP_TO_GROUND  ;
	}
	else if("2"===value){
		return  Cesium.HeightReference.RELATIVE_TO_GROUND  ;
	}
	else{
		return  Cesium.HorizontalOrigin.NONE;
	}
}	
VFG.Util.getVerticalOrigin = function(value){
	if("0"===value){
		return  Cesium.VerticalOrigin.BASELINE;
	}
	else if("1"===value){
		return  Cesium.VerticalOrigin.BOTTOM ;
	}
	else if("2"===value){
		return  Cesium.VerticalOrigin.CENTER ;
	}
	else if("3"===value){
		return  Cesium.VerticalOrigin.VerticalOrigin;
	}else{
		return  Cesium.VerticalOrigin.BASELINE;
	}
}

VFG.Util.getEntityForLine = function(data) {
	if(!data){
		return null;
	}
    var distanceDisplayCondition =VFG.Util.getDistanceDisplayCondition(data.distanceDisplayConditionX,data.distanceDisplayConditionY);
    var material=VFG.Util.getMaterialForLine(data);
    if(!material){
		return null;
	}
    
    return{
        show: true,
        positions: data.positions?data.positions:[],
		width : data.width*1,
		loop:data.loop&&data.loop=='1'?true:false,
		clampToGround:data.clampToGround&&data.clampToGround=='1'?true:false,
		material:material?material:Cesium.Color.RED,
		distanceDisplayCondition : distanceDisplayCondition?distanceDisplayCondition:undefined,
		zIndex: data.sort*1,		
	}
};

VFG.Util.getMaterialForLine = function(style,ctx){
	var _this=this;
	if(Cesium.defined(style)){
		if(style.materialType=="solid"){
			return (style.color)?Cesium.Color.fromCssColorString(style.color):Cesium.Color.RED;//线条颜色;
		}
		else if(style.materialType=="dash"){
			return new Cesium.PolylineDashMaterialProperty({
				color:(style.color)?Cesium.Color.fromCssColorString(style.color):Cesium.Color.RED,//线条颜色
				gapColor:(style.gapColor)?Cesium.Color.fromCssColorString(style.gapColor):Cesium.Color.WHITE,//间隔颜色
				dashLength:(style.dashLength)?style.dashLength*1:16,//间隔距离
				dashPattern:(style.dashPattern)?style.dashPattern*1:255.0
			})
		}
		else if(style.materialType=="outline"){
			return new Cesium.PolylineOutlineMaterialProperty({
				color:(style.color)?Cesium.Color.fromCssColorString(style.color):Cesium.Color.RED,//线条颜色
				outlineWidth: (style.outlineWidth)?style.outlineWidth*1:5,
				outlineColor:(style.outlineColor)?Cesium.Color.fromCssColorString(style.outlineColor):Cesium.Color.WHITE,//线条颜色
			});
		}
		else if(style.materialType=="glow"){
			return new Cesium.PolylineGlowMaterialProperty({
					color:(style.color)?Cesium.Color.fromCssColorString(style.color):Cesium.Color.RED,//线条颜色
					glowPower: (style.glowPower)?style.glowPower*1:0.5,//发光强度
				});
		}
		else if(style.materialType=="arrow"){
			return new Cesium.PolylineArrowMaterialProperty(
					(style.color)?Cesium.Color.fromCssColorString(style.color):Cesium.Color.RED
			);
		}
		else if(style.materialType=="od"){
			return new Cesium.ODLineMaterial(
					(style.color)?Cesium.Color.fromCssColorString(style.color):Cesium.Color.RED,style.interval?style.interval*1000:20000,style.direction,style.effect,ctx+"/"+style.imageUrl)
		}
		else{
			return Cesium.Color.BLUE;
		}
	}
}

VFG.Util.getEntityForPolygon = function(data) {
	var _this=this;
	var distanceDisplayCondition =VFG.Util.getDistanceDisplayCondition(data.distanceDisplayConditionX*1,data.distanceDisplayConditionY*1);
	
	var options={
		stRotation:data.stRotation?data.stRotation:0.0,
		fill:data.fill?data.fill:false,
		material:data.color? Cesium.Color.fromCssColorString(data.color):Cesium.Color.BLACK,
		outline:data.outline && data.outline=='1'  ?true:false,
		outlineColor:data.outlineColor? Cesium.Color.fromCssColorString(data.outlineColor):Cesium.Color.BLACK,
		outlineWidth:data.outlineWidth?data.outlineWidth*1:0.0,
		closeTop:data.closeTop?data.closeTop:false,
		closeBottom:data.closeBottom?data.closeBottom:false,
		arcType:Cesium.ArcType.GEODESIC,
		shadows:data.shadows?data.shadows:false,
		distanceDisplayCondition:distanceDisplayCondition||null,
		classificationType:_this.getClassificationType(data.classificationType)
	}
	
	var perPositionHeight=data.perPositionHeight && data.perPositionHeight=='1'  ?true:false;
	if(perPositionHeight){
		 options.height=data.height?data.height:0.0;
		 options.perPositionHeight=perPositionHeight;
		 options.heightReference=_this.getHeightReference(data.heightReference);
		 options.extrudedHeight=data.extrudedHeight?data.extrudedHeight:0.0;
		 options.extrudedHeightReference=_this.getHeightReference(data.extrudedHeightReference);
	}
	return options;
};

VFG.Util.getClassificationType = function(value) {
	if('1'==value){
		return Cesium.ClassificationType.TERRAIN;
	}
	else if('2'==value){
		return Cesium.ClassificationType.CESIUM_3D_TILE;
	}else{
		return Cesium.ClassificationType.BOTH;
	}
};

/**
 * 创建线段
 */
VFG.Util.createLinePrimitive=function(viewer,ops,polyline){
	if(polyline){
		return primitive =viewer.entities.add({
        	id:ops.id,
        	name:ops.name||'线',
        	show: true,
        	bizType:ops.code||'',
            polyline: polyline
        });
	}else{
		return primitive =viewer.entities.add({
        	id:ops.id,
        	name:ops.name||'线',
        	bizType:ops.code||'',
            polyline: {
                show: true,
                positions:ops.positions||[],
                material:Cesium.Color.RED,
                width:2
            }
        });
	}
}

/***
 * 创建多边形
 */
VFG.Util.createPolygonPrimitive=function(viewer,ops,polygon){
	viewer.entities.removeById(ops.id);
	if(polygon){
		return viewer.entities.add({
        	id:ops.id,
        	name:ops.name||'多边形',
        	show: true,
        	polygon: polygon
        });
	}else{
		return viewer.entities.add({
        	id:ops.id,
        	name:ops.name||'多边形',
        	show: true,
            polygon:{
                hierarchy : ops.hierarchy||[],
                perPositionHeight: true,
                material: Cesium.Color.RED.withAlpha(0.7),
                outline: true,
                outlineColor: Cesium.Color.YELLOW.withAlpha(1)
            }
        });
	}
}

VFG.Util.getHeightReference=function(value){
	if('RELATIVE_TO_GROUND'==value){
		return Cesium.HeightReference.RELATIVE_TO_GROUND;
	}
	else if('CLAMP_TO_GROUND'==value){
		return Cesium.HeightReference.CLAMP_TO_GROUND;
	}else{
		return Cesium.HeightReference.NONE;
	}
}

/**
 * 创建模型ForGLTF
 */
VFG.Util.createGltfPrimitive=function(viewer,ops){
	if(!ops){
		console.log('参数必填!!!');
		return;
	}
	
	if(!ops.uri){
		console.log('模型地址必填!!!');
		return;
	}
	
	if('GLTF'!=ops.type){
		console.log('模型格式必需是GLTF!!!');
		return;
	}
	if(!(ops.posX && ops.posY && ops.posZ)){
		console.log('坐标必填!!!');
		return;
	}
	if(!this.primitiveMap.has(ops.id)){
		var heading = Cesium.defaultValue(ops.heading, 0.0);
	    var pitch = Cesium.defaultValue(ops.pitch, 0.0);
	    var roll = Cesium.defaultValue(ops.roll, 0.0);
	    var headingPitchRoll = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(heading), Cesium.Math.toRadians(pitch), Cesium.Math.toRadians(roll));
		var distanceDisplayCondition =VFG.Util.getDistanceDisplayCondition(ops.displayNear,ops.displayFar);
		var origin = Cesium.Cartesian3.fromDegrees(ops.posX*1, ops.posY*1,ops.posZ*1);
		var modelMatrix =Cesium.Transforms.headingPitchRollToFixedFrame(origin, headingPitchRoll, Cesium.Ellipsoid.WGS84, Cesium.Transforms.eastNorthUpToFixedFrame, new Cesium.Matrix4());
		var model = viewer.scene.primitives.add(Cesium.Model.fromGltf({
			id:ops.id,
			name:ops.name||'未命名',
			url: ops.uri,
			type:ops.type,
			bizType:ops.code||'',
			show : ( ops.show &&  ops.show!='1')?false : true,                     
			modelMatrix : modelMatrix,
			scale: ops.scale*1||1,
			minimumPixelSize:(ops.minimumPixelSize)?ops.minimumPixelSize*1:0,
			maximumScale:(ops.minimumPixelSize)?ops.minimumPixelSize*1:undefined,
			allowPicking : true,        
			debugShowBoundingVolume : false, 
			debugWireframe : false,
			distanceDisplayCondition:distanceDisplayCondition?distanceDisplayCondition:undefined,
		}));
		model.readyPromise.then(function(model) {
		  model.activeAnimations.addAll();
		}).otherwise(function(error){
	    });
		this.primitiveMap.set(ops.id,model);
		return model;
	}else{
		return this.primitiveMap.get(ops.id);
	}
	
/*    var distanceDisplayCondition =VFG.Util.getDistanceDisplayCondition(ops.displayNear,ops.displayFar);
	var position = Cesium.Cartesian3.fromDegrees(ops.posX*1, ops.posY*1,ops.posZ*1)
	var entity=new Cesium.Entity({
		id:ops.id,
    	name:ops.name||'未命名',
	    show: true,
	    position: position,
	    orientation:Cesium.Transforms.headingPitchRollQuaternion(
    		 position,
	         new Cesium.HeadingPitchRoll(
	            Cesium.Math.toRadians(ops.heading*1||0), 
	            Cesium.Math.toRadians(ops.pitch*1||0),
	            Cesium.Math.toRadians(ops.roll*1||0)
			 )
	    ),
	    model:{
	    	uri: ops.uri,
	    	basePath: ops.basePath||'',
	    	scale: ops.scale*1||1,
	    	allowPicking:(ops.allowPicking && ops.allowPicking=='1')?true:false,
			minimumPixelSize:(ops.minimumPixelSize)?ops.minimumPixelSize*1:0,
			maximumScale:(ops.minimumPixelSize)?ops.minimumPixelSize*1:undefined,
		    distanceDisplayCondition:distanceDisplayCondition?distanceDisplayCondition:undefined,
		    HeightReference:this.getHeightReference(ops.heightReference)
	    }
	});*/
	//return viewer.entities.add(entity)
}

VFG.Util.getPrimitiveModelMatrix=function(ops){
    var ry = Cesium.defaultValue(ops.ry, 0.0);
    var rx = Cesium.defaultValue(ops.rx, 0.0);
    var rz = Cesium.defaultValue(ops.rz, 0.0);
    
    var transformPosition =Cesium.Cartesian3.fromDegrees(ops.x*1, ops.y*1,ops.z*1);
    var matrix = Cesium.Transforms.eastNorthUpToFixedFrame(transformPosition);
    var scale = Cesium.Matrix4.fromUniformScale(ops.scale*1);
    Cesium.Matrix4.multiply(matrix, scale, matrix);
    
    var rotationX = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(rx));
    var rotationY = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(ry));
    var rotationZ = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(rz));
    
    
    var rotationTranslationX = Cesium.Matrix4.fromRotationTranslation(rotationX);
    var rotationTranslationY = Cesium.Matrix4.fromRotationTranslation(rotationY);
    var rotationTranslationZ = Cesium.Matrix4.fromRotationTranslation(rotationZ);
    Cesium.Matrix4.multiply(matrix, rotationTranslationX, matrix);
    Cesium.Matrix4.multiply(matrix, rotationTranslationY, matrix);
    Cesium.Matrix4.multiply(matrix, rotationTranslationZ, matrix);
	return matrix;
}


VFG.Util.updatePrimitiveModelMatrix=function(ops){
	var heading = Cesium.defaultValue(ops.heading, 0.0);
	var pitch = Cesium.defaultValue(ops.pitch, 0.0);
	var roll = Cesium.defaultValue(ops.roll, 0.0);
    //旋转
   var mx = Cesium.Matrix3.fromRotationX(pitch);
   var my = Cesium.Matrix3.fromRotationY(heading);
   var mz = Cesium.Matrix3.fromRotationZ(roll);
   var rotationX = Cesium.Matrix4.fromRotationTranslation(mx);
   var rotationY = Cesium.Matrix4.fromRotationTranslation(my);
   var rotationZ = Cesium.Matrix4.fromRotationTranslation(mz);
   //平移
   var origin = Cesium.Cartesian3.fromDegrees(ops.posX*1, ops.posY*1,ops.posZ*1);
   var m = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
   //旋转、平移矩阵相乘
   Cesium.Matrix4.multiply(m, rotationX, m);
   Cesium.Matrix4.multiply(m, rotationY, m);
   Cesium.Matrix4.multiply(m, rotationZ, m);
   return m;
}

VFG.Util.create3DTilePrimitive=function(viewer,ops){
	if(!ops){
		console.log('参数必填!!!');
		return;
	}
	
	if(!ops.uri){
		console.log('模型地址必填!!!');
		return;
	}
	
	if('3DTILES'!=ops.type){
		console.log('模型格式必需是3DTILES!!!');
		return;
	}
	
	
	if(!this.primitiveMap.has(ops.id)){
		var primitive=viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
			id : ops.id,
			url : ops.uri,
			name : ops.name ||'未命名',
			show : ( ops.show &&  ops.show!='1')?false : true,    
			bizType:ops.code||'',
			preferLeaves:(ops && ops.preferLeaves && ops.preferLeaves=='1')?true:false,
			imageBasedLightingFactor :Cesium.Cartesian2(1.0, 1.0),
			loadSiblings:true,
			skipLevels:ops.skipLevels ? ops.skipLevels*1: 1,
			baseScreenSpaceError:ops.baseScreenSpaceError ? ops.baseScreenSpaceError*1: 1024,
			skipScreenSpaceErrorFactor:ops.skipScreenSpaceErrorFactor ? ops.skipScreenSpaceErrorFactor*1: 16,
			maximumMemoryUsage:ops.maximumMemoryUsage ? ops.maximumMemoryUsage*1: 512,
			maximumScreenSpaceError : ops.maximumScreenSpaceError ? ops.maximumScreenSpaceError*1: 16,
			skipLevelOfDetail : ops.skipLevelOfDetail ? (ops.skipLevelOfDetail=='on'?true:false): false,
			maximumNumberOfLoadedTiles : ops.maximumNumberOfLoadedTiles ? ops.maximumNumberOfLoadedTiles*1: 1024, //最大加载瓦片个数			
		}));
		
		primitive.readyPromise.then(function(tileset) {

			if(ops.posX && ops.posY && ops.posZ){
				  tileset._root.transform = VFG.Util.getPrimitiveModelMatrix(ops);
			}else{
	            var heightOffset =ops.z || 0;  //高度
	            var boundingSphere = tileset.boundingSphere; 
	            var cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);
	            var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
	            var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset);
	            var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
	            tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
			}
			
			
		    if(ops.callBack){
		    	var result=VFG.Util.getCenterForModel(tileset,tileset._root.transform);
		    	ops.callBack(result);
		    }
			
		}).otherwise(function(error){
			console.log(error);
	    });
		this.primitiveMap.set(ops.id,primitive);
		return primitive;
	}else{
		return this.primitiveMap.get(ops.id);
	}
}

//获取模型的中心点信息
VFG.Util.getCenterForModel=function(tileset, transform) {
    var result = {};

    //记录模型原始的中心点
    var boundingSphere = tileset.boundingSphere;
    var position = boundingSphere.center;
    var catographic = Cesium.Cartographic.fromCartesian(position);

    var height = Number(catographic.height.toFixed(2));
    var longitude = Number(Cesium.Math.toDegrees(catographic.longitude).toFixed(6));
    var latitude = Number(Cesium.Math.toDegrees(catographic.latitude).toFixed(6));
    result = { x: longitude, y: latitude, z: height };

    //console.log("模型内部原始位置:" + JSON.stringify(result));

    //如果tileset自带世界矩阵矩阵，那么计算放置的经纬度和heading
    if (transform) {
        var matrix = Cesium.Matrix4.fromArray(tileset._root.transform);
        var pos = Cesium.Matrix4.getTranslation(matrix, new Cesium.Cartesian3());
        var wpos = Cesium.Cartographic.fromCartesian(pos);
        if (Cesium.defined(wpos)) {
            result.x = Number(Cesium.Math.toDegrees(wpos.longitude).toFixed(6));
            result.y = Number(Cesium.Math.toDegrees(wpos.latitude).toFixed(6));
            result.z = Number(wpos.height.toFixed(2));

            //取旋转矩阵
            var rotmat = Cesium.Matrix4.getMatrix3(matrix, new Cesium.Matrix3());
            //默认的旋转矩阵
            var defrotmat = Cesium.Matrix4.getMatrix3(Cesium.Transforms.eastNorthUpToFixedFrame(pos), new Cesium.Matrix3());

            //计算rotmat 的x轴，在defrotmat 上 旋转
            var xaxis = Cesium.Matrix3.getColumn(defrotmat, 0, new Cesium.Cartesian3());
            var yaxis = Cesium.Matrix3.getColumn(defrotmat, 1, new Cesium.Cartesian3());
            var zaxis = Cesium.Matrix3.getColumn(defrotmat, 2, new Cesium.Cartesian3());

            var dir = Cesium.Matrix3.getColumn(rotmat, 0, new Cesium.Cartesian3());

            dir = Cesium.Cartesian3.cross(dir, zaxis, dir);
            dir = Cesium.Cartesian3.cross(zaxis, dir, dir);
            dir = Cesium.Cartesian3.normalize(dir, dir);

            var heading = Cesium.Cartesian3.angleBetween(xaxis, dir);

            var ay = Cesium.Cartesian3.angleBetween(yaxis, dir);

            if (ay > Math.PI * 0.5) {
                heading = 2 * Math.PI - heading;
            }
            result.rotation_x = 0;
            result.rotation_y = 0;
            result.rotation_z = Number(Cesium.Math.toDegrees(heading).toFixed(1));

            result.heading = result.rotation_z; //兼容v1老版本

           // console.log("模型内部世界矩阵:" + JSON.stringify(result));
        }
    }

    return result;
}

VFG.Util.getPrimitiveById=function(viewer,id){
	if(this.primitiveMap.has(id)){
		return this.primitiveMap.get(id);
	}
	return null;
}

VFG.Util.removePrimitive=function(viewer,id){
	if(this.primitiveMap.has(id)){
		if(viewer.scene.primitives.remove(this.primitiveMap.get(id))){
			this.primitiveMap.delete(id);
			return true;
		}
		return false;
	}else{
		return false;	
	}
	return false;
}

VFG.Util.removeAllPrimitive=function(viewer){
	this.primitiveMap.clear();
	return viewer.scene.primitives.removeAll();
}

/**
 * 移除场景元素
 * viewer
 * ops:{id:图层Id,type:图层类型}
 */
VFG.Util.removeScenePrimitive=function(viewer,ops){
	if('point'==ops.type){
		VFG.Point.removePointById(ops.id) 
	}
	else if('line'==ops.type){
		VFG.Util.removeEntityById(viewer,ops.id) 
	}
	else if('polygon'==ops.type){
		VFG.Util.removeEntityById(viewer,ops.id) 
	}
	if('Feature'==ops.type){
		VFG.Model.Feature.removeFeatureById(ops.id) 
	}
	else if('map'==ops.type){
		VFG.Provider.removeById(viewer,ops.id)
	}
	else if('terrain'==ops.type){
		VFG.Provider.removeTerrainProviderById(viewer,ops.id);
	}
	else if('division'==ops.type){
		VFG.Provider.removeById(viewer,ops.id)
	}
	else if('road'==ops.type){
		VFG.Provider.removeById(viewer,ops.id)
	}
	else if('GLTF'==ops.type){
		VFG.Util.removePrimitive(viewer,ops.id);
	}
	else if('3DTILES'==ops.type){
 		VFG.Util.removePrimitive(viewer,ops.id);
	}
}

/**
 * 显示隐藏
 */
VFG.Util.showScenePrimitive=function(viewer,ops){
	if('point'==ops.type){
		var entity=VFG.Point.getPointById(ops.id);
		if(entity){
			entity.show=ops.show;
		}
	}
	else if('line'==ops.type || 'polygon'==ops.type){
		var entity=viewer.entities.getById(ops.id);
		if(entity){
			entity.show=ops.show;
		}
	}
	else if('GLTF'==ops.type || '3DTILES'==ops.type){
		if(this.primitiveMap.has(ops.id)){
			this.primitiveMap.get(ops.id).show=ops.show;
		}
	}
}


VFG.Util.c3sToLnLas=function(viewer,positions){
	var LnLas=[];
	for(var i=0;i<positions.length;i++){
		LnLas.push(this.getC3ToLnLa(viewer,positions[i]));
	}
	return LnLas;
}

VFG.Util.polygonForCreate=function(viewer,polygonRender){
	var _this=this;
	if(!polygonRender){
		return;
	}
	var polygon=polygonRender.polygon;
	var styles=polygonRender.styles;
	if(!polygon){
		return;
	}
	var polygonStyle;
	if(polygon!=null && styles.length>0){
		polygonStyle=VFG.Util.getEntityForPolygon(styles[0]);
	}
	var entity=VFG.Util.getEntityById(viewer,polygon.id);
	if(entity){
		VFG.Util.removeEntityById(viewer,polygon.id);
	}
	var points=[];
	if(polygon.points){
		points=JSON.parse(polygon.points);
		if(points.length>=2){
			var arrForC3=[];
			for(var i=0;i<points.length;i++){
				arrForC3.push(Cesium.Cartesian3.fromDegrees(points[i].x*1,points[i].y*1,points[i].z*1));
			}
			if(polygonStyle){
				polygonStyle.hierarchy=new Cesium.PolygonHierarchy(arrForC3)
				polygonStyle.clampToGround= true //开启贴地
			}
			
			VFG.Util.createPolygonPrimitive(viewer,{
				id:polygon.id,
				name:polygon.name||'',
				hierarchy:new Cesium.PolygonHierarchy(arrForC3)
			},polygonStyle);
		}

	}else{
		console.log('无效数据polygon');
	}
}

//线
VFG.Util.polyLineForCreate=function(viewer,polyLineRender){
	var _this=this;
	if(!polyLineRender){
		return;
	}
	var line=polyLineRender.line;
	var styles=polyLineRender.styles;
	if(!line){
		return;
	}
	var lineStyle;
	if(line!=null && styles.length>0){
		lineStyle=VFG.Util.getEntityForLine(styles[0]);
	}
	var entity=VFG.Util.getEntityById(viewer,line.id);
	if(entity){
		VFG.Util.removeEntityById(viewer,line.id);
	}
	if(line.points){
		var points=JSON.parse(line.points);
		var arrForC3=[];
		for(var i=0;i<points.length;i++){
			arrForC3.push(Cesium.Cartesian3.fromDegrees(points[i].x*1,points[i].y*1,points[i].z*1));
		}
		
		if(lineStyle){
			lineStyle.positions=arrForC3;
		}
		VFG.Util.createLinePrimitive(viewer,{
			id:line.id,
			name:line.name,
			code:line.code||'',
			positions:arrForC3
		},lineStyle);
	}else{
		console.log('无效数据line');
	}
}

/**
 * 获取多边形中心位置
 */
VFG.Util.getCenterForPolygon=function(viewer,positions, height) {
    try {
        if (positions.length == 1) {
            return positions[0];
        } else if (positions.length == 2) {
            return Cesium.Cartesian3.midpoint(positions[0], positions[1], new Cesium.Cartesian3());
        }
        
        var LnLas=[];
        var points=[];
        for(var i=0;i<positions.length;i++){
        	var lnla=this.getC3ToLnLa(viewer, positions[i]);
        	LnLas.push(lnla);
        	points.push([lnla.x,lnla.y]);
        }
        points.push(points[0]);
        var ds=[points]
        var polygon = turf.polygon(ds);
        var center = turf.centerOfMass(polygon);
        var coordinates=center.geometry.coordinates;
        var cartesian3=new Cesium.Cartesian3.fromDegrees(coordinates[0],coordinates[1],0);
    	var cartesian2=Cesium.SceneTransforms.wgs84ToWindowCoordinates(viewer.scene,cartesian3);
    	if (viewer.scene.mode !== Cesium.SceneMode.MORPHING) {
    		var pickedObject = viewer.scene.pick(cartesian2);
    		if (viewer.scene.pickPositionSupported && pickedObject) {
    			var carto=new Cesium.Cartographic.fromDegrees(coordinates[0],coordinates[1])
    			var sampleHeight = viewer.scene.sampleHeight(carto);
    			return new Cesium.Cartesian3.fromDegrees(coordinates[0],coordinates[1],sampleHeight);
    		}else{
    			var carto=new Cesium.Cartographic.fromDegrees(coordinates[0],coordinates[1])
        		var heightTerrain =  viewer.scene.globe.getHeight(carto);
    			return new Cesium.Cartesian3.fromDegrees(coordinates[0],coordinates[1],heightTerrain);
    		}
    	}else{
			var carto=new Cesium.Cartographic.fromDegrees(coordinates[0],coordinates[1])
    		var heightTerrain =  viewer.scene.globe.getHeight(carto);
			return new Cesium.Cartesian3.fromDegrees(coordinates[0],coordinates[1],heightTerrain);
    	}
    } catch (e) {
    	console.log(e);
        return positions[Math.floor(positions.length / 2)];
    }
}

/**

 * 获取坐标数组中最高高程值
 * @param {Array} positions Array<Cartesian3> 笛卡尔坐标数组
 * @param {Number} defaultVal 默认高程值

 */
VFG.Util.getMaxHeight=function(positions, defaultVal) {
    if (defaultVal == null) defaultVal = 0;
    var maxHeight = defaultVal;
    if (positions == null || positions.length == 0) return maxHeight;
    for (var i = 0; i < positions.length; i++) {
        var tempCarto = Cesium.Cartographic.fromCartesian(positions[i]);
        if (tempCarto.height > maxHeight) {
            maxHeight = tempCarto.height;
        }
    }
    return formatNum(maxHeight, 2);
}

//格式化 数字 小数位数
VFG.Util.formatNum=function(num, digits) {
    return Number(num.toFixed(digits || 0));
}

/**
 * 获取高度
 */
VFG.Util.getSurfaceHeight=function (viewer, position, opts) {
	var _this=this;
	var cartesian2=Cesium.SceneTransforms.wgs84ToWindowCoordinates(viewer.scene,position);
	if (viewer.scene.mode !== Cesium.SceneMode.MORPHING && cartesian2) {
		var pickedObject = viewer.scene.pick(cartesian2);
		if (viewer.scene.pickPositionSupported && Cesium.defined(pickedObject)) {
			return _this.getSurface3DTilesetHeight(viewer, position, opts);
		}
	}
	return _this.getSurfaceTerrainHeight(viewer, position, opts);
}

//
///**
//
// * 获取坐标的 贴模型高度
// * opts支持:   是否异步 asyn:true  异步回调方法calback返回“新高度”和“原始的Cartographic坐标”
// */
//VFG.Util.getSurface3DTilesHeight=function(scene, position, opts) {
//	var _this=this;
//    opts = opts || {};
//    //原始的Cartographic坐标
//    opts.cartesian = opts.cartesian || Cesium.Cartographic.fromCartesian(position);
//    var carto = opts.cartesian;
//
//    //是否异步求精确高度 
//    if (opts.asyn) {
//    	 var cartographic=Cesium.Cartographic.fromCartesian(position);
//        scene.sampleHeightMostDetailed([cartographic]).then(function (clampedPositions) {
//            var clampedPt = clampedPositions[0];
//            if (Cesium.defined(clampedPt)) {
//                var heightTiles = clampedPt.height;
//                if (Cesium.defined(heightTiles) && heightTiles > -1000) {
//                    if (opts.calback) opts.calback(heightTiles, clampedPt);
//                    return;
//                }
//            }else{
//            	_this.getSurfaceTerrainHeight(scene, position, opts);
//            }
//        });
//    } else {
//        //取贴模型高度
//        var heightTiles = scene.sampleHeight(carto);
//        if (Cesium.defined(heightTiles) && heightTiles > -1000) {
//            if (opts.calback) opts.calback(heightTiles, carto);
//            return heightTiles;
//        }
//    }
//    return 0; //表示取值失败
//}

/**
 * 获取坐标的 贴地高度
 * opts支持:   是否异步 asyn:true  异步回调方法calback
 */
//VFG.Util.getSurfaceTerrainHeight=function(scene, position, opts) {
//    opts = opts || {};
//    //原始的Cartographic坐标
//    var carto = opts.cartesian || Cesium.Cartographic.fromCartesian(position);
//    var _hasTerrain = VFG.Provider.hasTerrain; //是否有地形
//    if (!_hasTerrain) {
//        //不存在地形，直接返回
//        if (opts.calback) opts.calback(carto.height, carto);
//        return carto.height;
//    }
//
//    //是否异步求精确高度 
//    if (opts.asyn) {
//        Cesium.when(Cesium.sampleTerrainMostDetailed(scene.terrainProvider, [carto]), function (samples) {
//            var clampedCart = samples[0];
//            var heightTerrain;
//            if (Cesium.defined(clampedCart) && Cesium.defined(clampedCart.height)) {
//                heightTerrain = clampedCart.height;
//            } else {
//                heightTerrain = scene.globe.getHeight(carto);
//            }
//            if (opts.calback) opts.calback(heightTerrain, carto);
//        });
//    } else {
//        var heightTerrain = scene.globe.getHeight(carto);
//        if (Cesium.defined(heightTerrain) && heightTerrain > -1000) {
//            if (opts.calback) opts.calback(heightTerrain, carto);
//            return heightTerrain;
//        }
//    }
//    return 0; //表示取值失败
//}

/**
 * 获取模型表面高度
 * viewer:
 * cartesian3:笛卡尔坐标
 * opts:{
 * 	asyn:true/false
 * 	calback(e)：e模型表面高度
 * }
 */
VFG.Util.getSurfaceModelHeight=function(viewer, cartesian3, opts) {
	var cartographic=Cesium.Cartographic.fromCartesian(cartesian3);
	if (Cesium.defined(cartographic)){
		  var objectsToExclude = [cartographic];
		  var height;
		  if (viewer.scene.sampleHeightSupported) {
			  if (opts.asyn){
				  viewer.scene.sampleHeightMostDetailed(objectsToExclude).then(function(updatedPosition) {
					  height= positions[0].height;
					  if (Cesium.defined(height)){
						  if (opts.calback) {
							  opts.calback(height);
						  }
					  }else{
						  if (opts.calback) {
							  opts.calback(0);
						  } 
					  }
				  });
			  }else{
				  height = viewer.scene.sampleHeight(cartographic, objectsToExclude);
				  if (Cesium.defined(height)){
					  return height;
				  }
			  }
		  }
	}
	return 0;
}

/**
 * 获取3DTileset表面高度
 * cartesian3 笛卡尔坐标
 */
VFG.Util.getSurface3DTilesetHeight=function(viewer, cartesian3, opts) {
	var _this=this;
	if(Cesium.defined(cartesian3)){
		if (viewer.scene.clampToHeightSupported){
			if (opts && opts.asyn){
				viewer.scene.clampToHeightMostDetailed([cartesian3]).then(function(clampedCartesians) {
					var clampedPt = clampedCartesians[0];
		            if (Cesium.defined(clampedPt)) {
		                var heightTiles = Cesium.Cartographic.fromCartesian(clampedPt).height;
		                if (Cesium.defined(heightTiles) && heightTiles > -1000) {
		                	if (opts.calback) opts.calback(heightTiles);
		                }else{
		                	_this.getSurfaceTerrainHeight(viewer, cartesian3, opts);
		                }
		            }else{
		            	_this.getSurfaceTerrainHeight(viewer, cartesian3, opts);
		            }
				});
			}else{
				var c3=viewer.scene.clampToHeight(cartesian3);
				if (Cesium.defined(c3)){
					var LnLa=VFG.Util.getC3ToLnLa(viewer, c3);
					if(Cesium.defined(LnLa) &&  LnLa.z>-1000){
						return LnLa.z;
					}else{
					 _this.getSurfaceTerrainHeight(viewer, cartesian3, opts);
					}
				}
			}
		}else{
			_this.getSurfaceTerrainHeight(viewer, cartesian3, opts);
		}
	}
}

/**
 * 获取地表高度
 */
VFG.Util.getSurfaceTerrainHeight=function(viewer, cartesian3, opts) {
	if (Cesium.defined(viewer.scene.terrainProvider)){
		var cartographic=Cesium.Cartographic.fromCartesian(cartesian3);
		if (Cesium.defined(cartographic)){
			  var _hasTerrain = VFG.Provider.hasTerrain; //是否有地形
			  if (!_hasTerrain) {
			      if (opts.calback) opts.calback(cartographic.height);
			      return cartographic.height;
			  }
			  var objectsToExclude = [cartographic];
			  if (opts.asyn){
				  Cesium.sampleTerrainMostDetailed(viewer.scene.terrainProvider,objectsToExclude).then(function(samples) {
					    var heightTerrain;
			            var clampedCart = samples[0];
			            if (Cesium.defined(clampedCart) && Cesium.defined(clampedCart.height)) {
			                heightTerrain = clampedCart.height;
			    			if(heightTerrain<0){
			    				console.log(heightTerrain);
			    			}
			            } else {
			                heightTerrain = viewer.scene.globe.getHeight(cartographic);
			            }
			            if (opts.calback) opts.calback(heightTerrain);
				  })
			  }else{
			        var heightTerrain = viewer.scene.globe.getHeight(cartographic);
			        if (Cesium.defined(heightTerrain) && heightTerrain > -1000) {
			            return heightTerrain;
			        }
			  }
		}	
	}
	return 0;
}


VFG.Util.getCurrentExtent=function(viewer) {
    // 范围对象
    var extent = {};

    // 得到当前三维场景
    var scene = viewer.scene;

    // 得到当前三维场景的椭球体
    var ellipsoid = scene.globe.ellipsoid;
    var canvas = scene.canvas;

    // canvas左上角
    var car3_lt = viewer.camera.pickEllipsoid(new Cesium.Cartesian2(0, 0), ellipsoid);

    // canvas右下角
    var car3_rb = viewer.camera.pickEllipsoid(new Cesium.Cartesian2(canvas.width, canvas.height), ellipsoid);

    // 当canvas左上角和右下角全部在椭球体上
    if (car3_lt && car3_rb) {
        var carto_lt = ellipsoid.cartesianToCartographic(car3_lt);
        var carto_rb = ellipsoid.cartesianToCartographic(car3_rb);
        extent.xmin = Cesium.Math.toDegrees(carto_lt.longitude);
        extent.ymax = Cesium.Math.toDegrees(carto_lt.latitude);
        extent.xmax = Cesium.Math.toDegrees(carto_rb.longitude);
        extent.ymin = Cesium.Math.toDegrees(carto_rb.latitude);
    }

    // 当canvas左上角不在但右下角在椭球体上
    else if (!car3_lt && car3_rb) {
        var car3_lt2 = null;
        var yIndex = 0;
        do {
            // 这里每次10像素递加，一是10像素相差不大，二是为了提高程序运行效率
            yIndex <= canvas.height ? yIndex += 10 : canvas.height;
            car3_lt2 = viewer.camera.pickEllipsoid(new Cesium.Cartesian2(0, yIndex), ellipsoid);
        } while (!car3_lt2);
        var carto_lt2 = ellipsoid.cartesianToCartographic(car3_lt2);
        var carto_rb2 = ellipsoid.cartesianToCartographic(car3_rb);
        extent.xmin = Cesium.Math.toDegrees(carto_lt2.longitude);
        extent.ymax = Cesium.Math.toDegrees(carto_lt2.latitude);
        extent.xmax = Cesium.Math.toDegrees(carto_rb2.longitude);
        extent.ymin = Cesium.Math.toDegrees(carto_rb2.latitude);
    }

    // 获取高度
    extent.height = Math.ceil(viewer.camera.positionCartographic.height);
    return extent;
}

/**
 * viewer:viewer
 * cameraPosition:起点
 * position:目标
 */
VFG.Util.getHeadingPitchRoll = function (viewer,cameraPosition,position) {
	var _this=this;
    var e = cameraPosition,
    t = position,
    i = Cesium.Cartesian3.normalize(Cesium.Cartesian3.subtract(t, e, new Cesium.Cartesian3), new Cesium.Cartesian3),
    a = Cesium.Cartesian3.normalize(e, new Cesium.Cartesian3),
    n = new Cesium.Camera(viewer.scene);
    n.position = e,
    n.direction = i,
    n.up = a,
    i = n.directionWC,
    a = n.upWC;
    var r = n.rightWC,
    o = new Cesium.Cartesian3,
    l = new Cesium.Matrix3,
    u = new Cesium.Quaternion;
    r = Cesium.Cartesian3.negate(r, o);
    var d = l;
    Cesium.Matrix3.setColumn(d, 0, r, d),
    Cesium.Matrix3.setColumn(d, 1, a, d),
    Cesium.Matrix3.setColumn(d, 2, i, d);
    var c = Cesium.Quaternion.fromRotationMatrix(d, u);
    var hpr = Cesium.HeadingPitchRoll.fromQuaternion(c);
    
    //return hpr;
    // 得到角度
/*    var heading = Cesium.Math.toDegrees(hpr.heading);
    var pitch = Cesium.Math.toDegrees(hpr.pitch);
    var roll = Cesium.Math.toDegrees(hpr.roll);*/
    return hpr
};

/**
 * Turf多边形
 */
VFG.Util.getTurfPolygon = function (points) {
	var area=[];
	for(var i=0;i<points.length;i++){
		var point=[];
		point[0]=points[i].x;
		point[1]=points[i].y;
		area.push(point);
	}
	
	var point=[];
	point[0]=points[0].x;
	point[1]=points[0].y;
	area.push(point);
	return turf.polygon([area]);
}

/**
 * Turf点
 */
VFG.Util.getTurfPoint = function (point) {
	return turf.point([point.x*1, point.y*1]);
}

/**
 * 点是否在多边形内部
 */
VFG.Util.booleanPointInPolygon = function (polygon,point) {
	return turf.booleanPointInPolygon(point,polygon);
}


;
///<jscompress sourcefile="viewerCesiumNavigationMixin.js" />
/**
 * Cesium Navigation - https://github.com/alberto-acevedo/cesium-navigation
 *
 * The plugin is 100% based on open source libraries. The same license that applies to Cesiumjs and terriajs applies also to this plugin. Feel free to use it,  modify it, and improve it.
 */
(function (root, factory) {
    'use strict';
    /*jshint sub:true*/

    if (typeof define === 'function' && define.amd) {
        if(require.specified('Cesium/Cesium')) {
            define(['Cesium/Cesium'], factory);
        } else if(require.specified('Cesium')) {
            define(['Cesium'], factory);
        } else {
            define([], factory);
        }
    } else {
        factory();
    }
}(typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : this, function (C) {

    if (typeof C === 'object' && C !== null) {
        Cesium = C;
    }

// <-- actual code


/**
 * @license almond 0.3.3 Copyright jQuery Foundation and other contributors.
 * Released under MIT license, http://github.com/requirejs/almond/LICENSE
 */
//Going sloppy to avoid 'use strict' string cost, but strict practices should
//be followed.
/*global setTimeout: false */

var requirejs, require, define;
(function (undef) {
    var main, req, makeMap, handlers,
        defined = {},
        waiting = {},
        config = {},
        defining = {},
        hasOwn = Object.prototype.hasOwnProperty,
        aps = [].slice,
        jsSuffixRegExp = /\.js$/;

    function hasProp(obj, prop) {
        return hasOwn.call(obj, prop);
    }

    /**
     * Given a relative module name, like ./something, normalize it to
     * a real name that can be mapped to a path.
     * @param {String} name the relative name
     * @param {String} baseName a real name that the name arg is relative
     * to.
     * @returns {String} normalized name
     */
    function normalize(name, baseName) {
        var nameParts, nameSegment, mapValue, foundMap, lastIndex,
            foundI, foundStarMap, starI, i, j, part, normalizedBaseParts,
            baseParts = baseName && baseName.split("/"),
            map = config.map,
            starMap = (map && map['*']) || {};

        //Adjust any relative paths.
        if (name) {
            name = name.split('/');
            lastIndex = name.length - 1;

            // If wanting node ID compatibility, strip .js from end
            // of IDs. Have to do this here, and not in nameToUrl
            // because node allows either .js or non .js to map
            // to same file.
            if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
                name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
            }

            // Starts with a '.' so need the baseName
            if (name[0].charAt(0) === '.' && baseParts) {
                //Convert baseName to array, and lop off the last part,
                //so that . matches that 'directory' and not name of the baseName's
                //module. For instance, baseName of 'one/two/three', maps to
                //'one/two/three.js', but we want the directory, 'one/two' for
                //this normalization.
                normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
                name = normalizedBaseParts.concat(name);
            }

            //start trimDots
            for (i = 0; i < name.length; i++) {
                part = name[i];
                if (part === '.') {
                    name.splice(i, 1);
                    i -= 1;
                } else if (part === '..') {
                    // If at the start, or previous value is still ..,
                    // keep them so that when converted to a path it may
                    // still work when converted to a path, even though
                    // as an ID it is less than ideal. In larger point
                    // releases, may be better to just kick out an error.
                    if (i === 0 || (i === 1 && name[2] === '..') || name[i - 1] === '..') {
                        continue;
                    } else if (i > 0) {
                        name.splice(i - 1, 2);
                        i -= 2;
                    }
                }
            }
            //end trimDots

            name = name.join('/');
        }

        //Apply map config if available.
        if ((baseParts || starMap) && map) {
            nameParts = name.split('/');

            for (i = nameParts.length; i > 0; i -= 1) {
                nameSegment = nameParts.slice(0, i).join("/");

                if (baseParts) {
                    //Find the longest baseName segment match in the config.
                    //So, do joins on the biggest to smallest lengths of baseParts.
                    for (j = baseParts.length; j > 0; j -= 1) {
                        mapValue = map[baseParts.slice(0, j).join('/')];

                        //baseName segment has  config, find if it has one for
                        //this name.
                        if (mapValue) {
                            mapValue = mapValue[nameSegment];
                            if (mapValue) {
                                //Match, update name to the new value.
                                foundMap = mapValue;
                                foundI = i;
                                break;
                            }
                        }
                    }
                }

                if (foundMap) {
                    break;
                }

                //Check for a star map match, but just hold on to it,
                //if there is a shorter segment match later in a matching
                //config, then favor over this star map.
                if (!foundStarMap && starMap && starMap[nameSegment]) {
                    foundStarMap = starMap[nameSegment];
                    starI = i;
                }
            }

            if (!foundMap && foundStarMap) {
                foundMap = foundStarMap;
                foundI = starI;
            }

            if (foundMap) {
                nameParts.splice(0, foundI, foundMap);
                name = nameParts.join('/');
            }
        }

        return name;
    }

    function makeRequire(relName, forceSync) {
        return function () {
            //A version of a require function that passes a moduleName
            //value for items that may need to
            //look up paths relative to the moduleName
            var args = aps.call(arguments, 0);

            //If first arg is not require('string'), and there is only
            //one arg, it is the array form without a callback. Insert
            //a null so that the following concat is correct.
            if (typeof args[0] !== 'string' && args.length === 1) {
                args.push(null);
            }
            return req.apply(undef, args.concat([relName, forceSync]));
        };
    }

    function makeNormalize(relName) {
        return function (name) {
            return normalize(name, relName);
        };
    }

    function makeLoad(depName) {
        return function (value) {
            defined[depName] = value;
        };
    }

    function callDep(name) {
        if (hasProp(waiting, name)) {
            var args = waiting[name];
            delete waiting[name];
            defining[name] = true;
            main.apply(undef, args);
        }

        if (!hasProp(defined, name) && !hasProp(defining, name)) {
            throw new Error('No ' + name);
        }
        return defined[name];
    }

    //Turns a plugin!resource to [plugin, resource]
    //with the plugin being undefined if the name
    //did not have a plugin prefix.
    function splitPrefix(name) {
        var prefix,
            index = name ? name.indexOf('!') : -1;
        if (index > -1) {
            prefix = name.substring(0, index);
            name = name.substring(index + 1, name.length);
        }
        return [prefix, name];
    }

    //Creates a parts array for a relName where first part is plugin ID,
    //second part is resource ID. Assumes relName has already been normalized.
    function makeRelParts(relName) {
        return relName ? splitPrefix(relName) : [];
    }

    /**
     * Makes a name map, normalizing the name, and using a plugin
     * for normalization if necessary. Grabs a ref to plugin
     * too, as an optimization.
     */
    makeMap = function (name, relParts) {
        var plugin,
            parts = splitPrefix(name),
            prefix = parts[0],
            relResourceName = relParts[1];

        name = parts[1];

        if (prefix) {
            prefix = normalize(prefix, relResourceName);
            plugin = callDep(prefix);
        }

        //Normalize according
        if (prefix) {
            if (plugin && plugin.normalize) {
                name = plugin.normalize(name, makeNormalize(relResourceName));
            } else {
                name = normalize(name, relResourceName);
            }
        } else {
            name = normalize(name, relResourceName);
            parts = splitPrefix(name);
            prefix = parts[0];
            name = parts[1];
            if (prefix) {
                plugin = callDep(prefix);
            }
        }

        //Using ridiculous property names for space reasons
        return {
            f: prefix ? prefix + '!' + name : name, //fullName
            n: name,
            pr: prefix,
            p: plugin
        };
    };

    function makeConfig(name) {
        return function () {
            return (config && config.config && config.config[name]) || {};
        };
    }

    handlers = {
        require: function (name) {
            return makeRequire(name);
        },
        exports: function (name) {
            var e = defined[name];
            if (typeof e !== 'undefined') {
                return e;
            } else {
                return (defined[name] = {});
            }
        },
        module: function (name) {
            return {
                id: name,
                uri: '',
                exports: defined[name],
                config: makeConfig(name)
            };
        }
    };

    main = function (name, deps, callback, relName) {
        var cjsModule, depName, ret, map, i, relParts,
            args = [],
            callbackType = typeof callback,
            usingExports;

        //Use name if no relName
        relName = relName || name;
        relParts = makeRelParts(relName);

        //Call the callback to define the module, if necessary.
        if (callbackType === 'undefined' || callbackType === 'function') {
            //Pull out the defined dependencies and pass the ordered
            //values to the callback.
            //Default to [require, exports, module] if no deps
            deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
            for (i = 0; i < deps.length; i += 1) {
                map = makeMap(deps[i], relParts);
                depName = map.f;

                //Fast path CommonJS standard dependencies.
                if (depName === "require") {
                    args[i] = handlers.require(name);
                } else if (depName === "exports") {
                    //CommonJS module spec 1.1
                    args[i] = handlers.exports(name);
                    usingExports = true;
                } else if (depName === "module") {
                    //CommonJS module spec 1.1
                    cjsModule = args[i] = handlers.module(name);
                } else if (hasProp(defined, depName) ||
                           hasProp(waiting, depName) ||
                           hasProp(defining, depName)) {
                    args[i] = callDep(depName);
                } else if (map.p) {
                    map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
                    args[i] = defined[depName];
                } else {
                    throw new Error(name + ' missing ' + depName);
                }
            }

            ret = callback ? callback.apply(defined[name], args) : undefined;

            if (name) {
                //If setting exports via "module" is in play,
                //favor that over return value and exports. After that,
                //favor a non-undefined return value over exports use.
                if (cjsModule && cjsModule.exports !== undef &&
                        cjsModule.exports !== defined[name]) {
                    defined[name] = cjsModule.exports;
                } else if (ret !== undef || !usingExports) {
                    //Use the return value from the function.
                    defined[name] = ret;
                }
            }
        } else if (name) {
            //May just be an object definition for the module. Only
            //worry about defining if have a module name.
            defined[name] = callback;
        }
    };

    requirejs = require = req = function (deps, callback, relName, forceSync, alt) {
        if (typeof deps === "string") {
            if (handlers[deps]) {
                //callback in this case is really relName
                return handlers[deps](callback);
            }
            //Just return the module wanted. In this scenario, the
            //deps arg is the module name, and second arg (if passed)
            //is just the relName.
            //Normalize module name, if it contains . or ..
            return callDep(makeMap(deps, makeRelParts(callback)).f);
        } else if (!deps.splice) {
            //deps is a config object, not an array.
            config = deps;
            if (config.deps) {
                req(config.deps, config.callback);
            }
            if (!callback) {
                return;
            }

            if (callback.splice) {
                //callback is an array, which means it is a dependency list.
                //Adjust args if there are dependencies
                deps = callback;
                callback = relName;
                relName = null;
            } else {
                deps = undef;
            }
        }

        //Support require(['a'])
        callback = callback || function () {};

        //If relName is a function, it is an errback handler,
        //so remove it.
        if (typeof relName === 'function') {
            relName = forceSync;
            forceSync = alt;
        }

        //Simulate async callback;
        if (forceSync) {
            main(undef, deps, callback, relName);
        } else {
            //Using a non-zero value because of concern for what old browsers
            //do, and latest browsers "upgrade" to 4 if lower value is used:
            //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout:
            //If want a value immediately, use require('id') instead -- something
            //that works in almond on the global level, but not guaranteed and
            //unlikely to work in other AMD implementations.
            setTimeout(function () {
                main(undef, deps, callback, relName);
            }, 4);
        }

        return req;
    };

    /**
     * Just drops the config on the floor, but returns req in case
     * the config return value is used.
     */
    req.config = function (cfg) {
        return req(cfg);
    };

    /**
     * Expose module registry for debugging and tooling
     */
    requirejs._defined = defined;

    define = function (name, deps, callback) {
        if (typeof name !== 'string') {
            throw new Error('See almond README: incorrect module build, no module name');
        }

        //This module may not have dependencies
        if (!deps.splice) {
            //deps is not an array, so probably means
            //an object literal or factory function for
            //the value. Adjust args.
            callback = deps;
            deps = [];
        }

        if (!hasProp(defined, name) && !hasProp(waiting, name)) {
            waiting[name] = [name, deps, callback];
        }
    };

    define.amd = {
        jQuery: true
    };
}());

define("almond", function(){});

/*!
 * Knockout JavaScript library v3.5.1
 * (c) The Knockout.js team - http://knockoutjs.com/
 * License: MIT (http://www.opensource.org/licenses/mit-license.php)
 */

(function() {(function(n){var A=this||(0,eval)("this"),w=A.document,R=A.navigator,v=A.jQuery,H=A.JSON;v||"undefined"===typeof jQuery||(v=jQuery);(function(n){"function"===typeof define&&define.amd?define('knockout',["exports","require"],n):"object"===typeof exports&&"object"===typeof module?n(module.exports||exports):n(A.ko={})})(function(S,T){function K(a,c){return null===a||typeof a in W?a===c:!1}function X(b,c){var d;return function(){d||(d=a.a.setTimeout(function(){d=n;b()},c))}}function Y(b,c){var d;return function(){clearTimeout(d);
d=a.a.setTimeout(b,c)}}function Z(a,c){c&&"change"!==c?"beforeChange"===c?this.pc(a):this.gb(a,c):this.qc(a)}function aa(a,c){null!==c&&c.s&&c.s()}function ba(a,c){var d=this.qd,e=d[r];e.ra||(this.Qb&&this.mb[c]?(d.uc(c,a,this.mb[c]),this.mb[c]=null,--this.Qb):e.I[c]||d.uc(c,a,e.J?{da:a}:d.$c(a)),a.Ja&&a.gd())}var a="undefined"!==typeof S?S:{};a.b=function(b,c){for(var d=b.split("."),e=a,f=0;f<d.length-1;f++)e=e[d[f]];e[d[d.length-1]]=c};a.L=function(a,c,d){a[c]=d};a.version="3.5.1";a.b("version",
a.version);a.options={deferUpdates:!1,useOnlyNativeEvents:!1,foreachHidesDestroyed:!1};a.a=function(){function b(a,b){for(var c in a)f.call(a,c)&&b(c,a[c])}function c(a,b){if(b)for(var c in b)f.call(b,c)&&(a[c]=b[c]);return a}function d(a,b){a.__proto__=b;return a}function e(b,c,d,e){var l=b[c].match(q)||[];a.a.D(d.match(q),function(b){a.a.Na(l,b,e)});b[c]=l.join(" ")}var f=Object.prototype.hasOwnProperty,g={__proto__:[]}instanceof Array,h="function"===typeof Symbol,m={},k={};m[R&&/Firefox\/2/i.test(R.userAgent)?
"KeyboardEvent":"UIEvents"]=["keyup","keydown","keypress"];m.MouseEvents="click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave".split(" ");b(m,function(a,b){if(b.length)for(var c=0,d=b.length;c<d;c++)k[b[c]]=a});var l={propertychange:!0},p=w&&function(){for(var a=3,b=w.createElement("div"),c=b.getElementsByTagName("i");b.innerHTML="\x3c!--[if gt IE "+ ++a+"]><i></i><![endif]--\x3e",c[0];);return 4<a?a:n}(),q=/\S+/g,t;return{Jc:["authenticity_token",/^__RequestVerificationToken(_.*)?$/],
D:function(a,b,c){for(var d=0,e=a.length;d<e;d++)b.call(c,a[d],d,a)},A:"function"==typeof Array.prototype.indexOf?function(a,b){return Array.prototype.indexOf.call(a,b)}:function(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1},Lb:function(a,b,c){for(var d=0,e=a.length;d<e;d++)if(b.call(c,a[d],d,a))return a[d];return n},Pa:function(b,c){var d=a.a.A(b,c);0<d?b.splice(d,1):0===d&&b.shift()},wc:function(b){var c=[];b&&a.a.D(b,function(b){0>a.a.A(c,b)&&c.push(b)});return c},Mb:function(a,
b,c){var d=[];if(a)for(var e=0,l=a.length;e<l;e++)d.push(b.call(c,a[e],e));return d},jb:function(a,b,c){var d=[];if(a)for(var e=0,l=a.length;e<l;e++)b.call(c,a[e],e)&&d.push(a[e]);return d},Nb:function(a,b){if(b instanceof Array)a.push.apply(a,b);else for(var c=0,d=b.length;c<d;c++)a.push(b[c]);return a},Na:function(b,c,d){var e=a.a.A(a.a.bc(b),c);0>e?d&&b.push(c):d||b.splice(e,1)},Ba:g,extend:c,setPrototypeOf:d,Ab:g?d:c,P:b,Ga:function(a,b,c){if(!a)return a;var d={},e;for(e in a)f.call(a,e)&&(d[e]=
b.call(c,a[e],e,a));return d},Tb:function(b){for(;b.firstChild;)a.removeNode(b.firstChild)},Yb:function(b){b=a.a.la(b);for(var c=(b[0]&&b[0].ownerDocument||w).createElement("div"),d=0,e=b.length;d<e;d++)c.appendChild(a.oa(b[d]));return c},Ca:function(b,c){for(var d=0,e=b.length,l=[];d<e;d++){var k=b[d].cloneNode(!0);l.push(c?a.oa(k):k)}return l},va:function(b,c){a.a.Tb(b);if(c)for(var d=0,e=c.length;d<e;d++)b.appendChild(c[d])},Xc:function(b,c){var d=b.nodeType?[b]:b;if(0<d.length){for(var e=d[0],
l=e.parentNode,k=0,f=c.length;k<f;k++)l.insertBefore(c[k],e);k=0;for(f=d.length;k<f;k++)a.removeNode(d[k])}},Ua:function(a,b){if(a.length){for(b=8===b.nodeType&&b.parentNode||b;a.length&&a[0].parentNode!==b;)a.splice(0,1);for(;1<a.length&&a[a.length-1].parentNode!==b;)a.length--;if(1<a.length){var c=a[0],d=a[a.length-1];for(a.length=0;c!==d;)a.push(c),c=c.nextSibling;a.push(d)}}return a},Zc:function(a,b){7>p?a.setAttribute("selected",b):a.selected=b},Db:function(a){return null===a||a===n?"":a.trim?
a.trim():a.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")},Ud:function(a,b){a=a||"";return b.length>a.length?!1:a.substring(0,b.length)===b},vd:function(a,b){if(a===b)return!0;if(11===a.nodeType)return!1;if(b.contains)return b.contains(1!==a.nodeType?a.parentNode:a);if(b.compareDocumentPosition)return 16==(b.compareDocumentPosition(a)&16);for(;a&&a!=b;)a=a.parentNode;return!!a},Sb:function(b){return a.a.vd(b,b.ownerDocument.documentElement)},kd:function(b){return!!a.a.Lb(b,a.a.Sb)},R:function(a){return a&&
a.tagName&&a.tagName.toLowerCase()},Ac:function(b){return a.onError?function(){try{return b.apply(this,arguments)}catch(c){throw a.onError&&a.onError(c),c;}}:b},setTimeout:function(b,c){return setTimeout(a.a.Ac(b),c)},Gc:function(b){setTimeout(function(){a.onError&&a.onError(b);throw b;},0)},B:function(b,c,d){var e=a.a.Ac(d);d=l[c];if(a.options.useOnlyNativeEvents||d||!v)if(d||"function"!=typeof b.addEventListener)if("undefined"!=typeof b.attachEvent){var k=function(a){e.call(b,a)},f="on"+c;b.attachEvent(f,
k);a.a.K.za(b,function(){b.detachEvent(f,k)})}else throw Error("Browser doesn't support addEventListener or attachEvent");else b.addEventListener(c,e,!1);else t||(t="function"==typeof v(b).on?"on":"bind"),v(b)[t](c,e)},Fb:function(b,c){if(!b||!b.nodeType)throw Error("element must be a DOM node when calling triggerEvent");var d;"input"===a.a.R(b)&&b.type&&"click"==c.toLowerCase()?(d=b.type,d="checkbox"==d||"radio"==d):d=!1;if(a.options.useOnlyNativeEvents||!v||d)if("function"==typeof w.createEvent)if("function"==
typeof b.dispatchEvent)d=w.createEvent(k[c]||"HTMLEvents"),d.initEvent(c,!0,!0,A,0,0,0,0,0,!1,!1,!1,!1,0,b),b.dispatchEvent(d);else throw Error("The supplied element doesn't support dispatchEvent");else if(d&&b.click)b.click();else if("undefined"!=typeof b.fireEvent)b.fireEvent("on"+c);else throw Error("Browser doesn't support triggering events");else v(b).trigger(c)},f:function(b){return a.O(b)?b():b},bc:function(b){return a.O(b)?b.v():b},Eb:function(b,c,d){var l;c&&("object"===typeof b.classList?
(l=b.classList[d?"add":"remove"],a.a.D(c.match(q),function(a){l.call(b.classList,a)})):"string"===typeof b.className.baseVal?e(b.className,"baseVal",c,d):e(b,"className",c,d))},Bb:function(b,c){var d=a.a.f(c);if(null===d||d===n)d="";var e=a.h.firstChild(b);!e||3!=e.nodeType||a.h.nextSibling(e)?a.h.va(b,[b.ownerDocument.createTextNode(d)]):e.data=d;a.a.Ad(b)},Yc:function(a,b){a.name=b;if(7>=p)try{var c=a.name.replace(/[&<>'"]/g,function(a){return"&#"+a.charCodeAt(0)+";"});a.mergeAttributes(w.createElement("<input name='"+
c+"'/>"),!1)}catch(d){}},Ad:function(a){9<=p&&(a=1==a.nodeType?a:a.parentNode,a.style&&(a.style.zoom=a.style.zoom))},wd:function(a){if(p){var b=a.style.width;a.style.width=0;a.style.width=b}},Pd:function(b,c){b=a.a.f(b);c=a.a.f(c);for(var d=[],e=b;e<=c;e++)d.push(e);return d},la:function(a){for(var b=[],c=0,d=a.length;c<d;c++)b.push(a[c]);return b},Da:function(a){return h?Symbol(a):a},Zd:6===p,$d:7===p,W:p,Lc:function(b,c){for(var d=a.a.la(b.getElementsByTagName("input")).concat(a.a.la(b.getElementsByTagName("textarea"))),
e="string"==typeof c?function(a){return a.name===c}:function(a){return c.test(a.name)},l=[],k=d.length-1;0<=k;k--)e(d[k])&&l.push(d[k]);return l},Nd:function(b){return"string"==typeof b&&(b=a.a.Db(b))?H&&H.parse?H.parse(b):(new Function("return "+b))():null},hc:function(b,c,d){if(!H||!H.stringify)throw Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js");
return H.stringify(a.a.f(b),c,d)},Od:function(c,d,e){e=e||{};var l=e.params||{},k=e.includeFields||this.Jc,f=c;if("object"==typeof c&&"form"===a.a.R(c))for(var f=c.action,h=k.length-1;0<=h;h--)for(var g=a.a.Lc(c,k[h]),m=g.length-1;0<=m;m--)l[g[m].name]=g[m].value;d=a.a.f(d);var p=w.createElement("form");p.style.display="none";p.action=f;p.method="post";for(var q in d)c=w.createElement("input"),c.type="hidden",c.name=q,c.value=a.a.hc(a.a.f(d[q])),p.appendChild(c);b(l,function(a,b){var c=w.createElement("input");
c.type="hidden";c.name=a;c.value=b;p.appendChild(c)});w.body.appendChild(p);e.submitter?e.submitter(p):p.submit();setTimeout(function(){p.parentNode.removeChild(p)},0)}}}();a.b("utils",a.a);a.b("utils.arrayForEach",a.a.D);a.b("utils.arrayFirst",a.a.Lb);a.b("utils.arrayFilter",a.a.jb);a.b("utils.arrayGetDistinctValues",a.a.wc);a.b("utils.arrayIndexOf",a.a.A);a.b("utils.arrayMap",a.a.Mb);a.b("utils.arrayPushAll",a.a.Nb);a.b("utils.arrayRemoveItem",a.a.Pa);a.b("utils.cloneNodes",a.a.Ca);a.b("utils.createSymbolOrString",
a.a.Da);a.b("utils.extend",a.a.extend);a.b("utils.fieldsIncludedWithJsonPost",a.a.Jc);a.b("utils.getFormFields",a.a.Lc);a.b("utils.objectMap",a.a.Ga);a.b("utils.peekObservable",a.a.bc);a.b("utils.postJson",a.a.Od);a.b("utils.parseJson",a.a.Nd);a.b("utils.registerEventHandler",a.a.B);a.b("utils.stringifyJson",a.a.hc);a.b("utils.range",a.a.Pd);a.b("utils.toggleDomNodeCssClass",a.a.Eb);a.b("utils.triggerEvent",a.a.Fb);a.b("utils.unwrapObservable",a.a.f);a.b("utils.objectForEach",a.a.P);a.b("utils.addOrRemoveItem",
a.a.Na);a.b("utils.setTextContent",a.a.Bb);a.b("unwrap",a.a.f);Function.prototype.bind||(Function.prototype.bind=function(a){var c=this;if(1===arguments.length)return function(){return c.apply(a,arguments)};var d=Array.prototype.slice.call(arguments,1);return function(){var e=d.slice(0);e.push.apply(e,arguments);return c.apply(a,e)}});a.a.g=new function(){var b=0,c="__ko__"+(new Date).getTime(),d={},e,f;a.a.W?(e=function(a,e){var f=a[c];if(!f||"null"===f||!d[f]){if(!e)return n;f=a[c]="ko"+b++;d[f]=
{}}return d[f]},f=function(a){var b=a[c];return b?(delete d[b],a[c]=null,!0):!1}):(e=function(a,b){var d=a[c];!d&&b&&(d=a[c]={});return d},f=function(a){return a[c]?(delete a[c],!0):!1});return{get:function(a,b){var c=e(a,!1);return c&&c[b]},set:function(a,b,c){(a=e(a,c!==n))&&(a[b]=c)},Ub:function(a,b,c){a=e(a,!0);return a[b]||(a[b]=c)},clear:f,Z:function(){return b++ +c}}};a.b("utils.domData",a.a.g);a.b("utils.domData.clear",a.a.g.clear);a.a.K=new function(){function b(b,c){var d=a.a.g.get(b,e);
d===n&&c&&(d=[],a.a.g.set(b,e,d));return d}function c(c){var e=b(c,!1);if(e)for(var e=e.slice(0),k=0;k<e.length;k++)e[k](c);a.a.g.clear(c);a.a.K.cleanExternalData(c);g[c.nodeType]&&d(c.childNodes,!0)}function d(b,d){for(var e=[],l,f=0;f<b.length;f++)if(!d||8===b[f].nodeType)if(c(e[e.length]=l=b[f]),b[f]!==l)for(;f--&&-1==a.a.A(e,b[f]););}var e=a.a.g.Z(),f={1:!0,8:!0,9:!0},g={1:!0,9:!0};return{za:function(a,c){if("function"!=typeof c)throw Error("Callback must be a function");b(a,!0).push(c)},yb:function(c,
d){var f=b(c,!1);f&&(a.a.Pa(f,d),0==f.length&&a.a.g.set(c,e,n))},oa:function(b){a.u.G(function(){f[b.nodeType]&&(c(b),g[b.nodeType]&&d(b.getElementsByTagName("*")))});return b},removeNode:function(b){a.oa(b);b.parentNode&&b.parentNode.removeChild(b)},cleanExternalData:function(a){v&&"function"==typeof v.cleanData&&v.cleanData([a])}}};a.oa=a.a.K.oa;a.removeNode=a.a.K.removeNode;a.b("cleanNode",a.oa);a.b("removeNode",a.removeNode);a.b("utils.domNodeDisposal",a.a.K);a.b("utils.domNodeDisposal.addDisposeCallback",
a.a.K.za);a.b("utils.domNodeDisposal.removeDisposeCallback",a.a.K.yb);(function(){var b=[0,"",""],c=[1,"<table>","</table>"],d=[3,"<table><tbody><tr>","</tr></tbody></table>"],e=[1,"<select multiple='multiple'>","</select>"],f={thead:c,tbody:c,tfoot:c,tr:[2,"<table><tbody>","</tbody></table>"],td:d,th:d,option:e,optgroup:e},g=8>=a.a.W;a.a.ua=function(c,d){var e;if(v)if(v.parseHTML)e=v.parseHTML(c,d)||[];else{if((e=v.clean([c],d))&&e[0]){for(var l=e[0];l.parentNode&&11!==l.parentNode.nodeType;)l=l.parentNode;
l.parentNode&&l.parentNode.removeChild(l)}}else{(e=d)||(e=w);var l=e.parentWindow||e.defaultView||A,p=a.a.Db(c).toLowerCase(),q=e.createElement("div"),t;t=(p=p.match(/^(?:\x3c!--.*?--\x3e\s*?)*?<([a-z]+)[\s>]/))&&f[p[1]]||b;p=t[0];t="ignored<div>"+t[1]+c+t[2]+"</div>";"function"==typeof l.innerShiv?q.appendChild(l.innerShiv(t)):(g&&e.body.appendChild(q),q.innerHTML=t,g&&q.parentNode.removeChild(q));for(;p--;)q=q.lastChild;e=a.a.la(q.lastChild.childNodes)}return e};a.a.Md=function(b,c){var d=a.a.ua(b,
c);return d.length&&d[0].parentElement||a.a.Yb(d)};a.a.fc=function(b,c){a.a.Tb(b);c=a.a.f(c);if(null!==c&&c!==n)if("string"!=typeof c&&(c=c.toString()),v)v(b).html(c);else for(var d=a.a.ua(c,b.ownerDocument),e=0;e<d.length;e++)b.appendChild(d[e])}})();a.b("utils.parseHtmlFragment",a.a.ua);a.b("utils.setHtml",a.a.fc);a.aa=function(){function b(c,e){if(c)if(8==c.nodeType){var f=a.aa.Uc(c.nodeValue);null!=f&&e.push({ud:c,Kd:f})}else if(1==c.nodeType)for(var f=0,g=c.childNodes,h=g.length;f<h;f++)b(g[f],
e)}var c={};return{Xb:function(a){if("function"!=typeof a)throw Error("You can only pass a function to ko.memoization.memoize()");var b=(4294967296*(1+Math.random())|0).toString(16).substring(1)+(4294967296*(1+Math.random())|0).toString(16).substring(1);c[b]=a;return"\x3c!--[ko_memo:"+b+"]--\x3e"},bd:function(a,b){var f=c[a];if(f===n)throw Error("Couldn't find any memo with ID "+a+". Perhaps it's already been unmemoized.");try{return f.apply(null,b||[]),!0}finally{delete c[a]}},cd:function(c,e){var f=
[];b(c,f);for(var g=0,h=f.length;g<h;g++){var m=f[g].ud,k=[m];e&&a.a.Nb(k,e);a.aa.bd(f[g].Kd,k);m.nodeValue="";m.parentNode&&m.parentNode.removeChild(m)}},Uc:function(a){return(a=a.match(/^\[ko_memo\:(.*?)\]$/))?a[1]:null}}}();a.b("memoization",a.aa);a.b("memoization.memoize",a.aa.Xb);a.b("memoization.unmemoize",a.aa.bd);a.b("memoization.parseMemoText",a.aa.Uc);a.b("memoization.unmemoizeDomNodeAndDescendants",a.aa.cd);a.na=function(){function b(){if(f)for(var b=f,c=0,d;h<f;)if(d=e[h++]){if(h>b){if(5E3<=
++c){h=f;a.a.Gc(Error("'Too much recursion' after processing "+c+" task groups."));break}b=f}try{d()}catch(p){a.a.Gc(p)}}}function c(){b();h=f=e.length=0}var d,e=[],f=0,g=1,h=0;A.MutationObserver?d=function(a){var b=w.createElement("div");(new MutationObserver(a)).observe(b,{attributes:!0});return function(){b.classList.toggle("foo")}}(c):d=w&&"onreadystatechange"in w.createElement("script")?function(a){var b=w.createElement("script");b.onreadystatechange=function(){b.onreadystatechange=null;w.documentElement.removeChild(b);
b=null;a()};w.documentElement.appendChild(b)}:function(a){setTimeout(a,0)};return{scheduler:d,zb:function(b){f||a.na.scheduler(c);e[f++]=b;return g++},cancel:function(a){a=a-(g-f);a>=h&&a<f&&(e[a]=null)},resetForTesting:function(){var a=f-h;h=f=e.length=0;return a},Sd:b}}();a.b("tasks",a.na);a.b("tasks.schedule",a.na.zb);a.b("tasks.runEarly",a.na.Sd);a.Ta={throttle:function(b,c){b.throttleEvaluation=c;var d=null;return a.$({read:b,write:function(e){clearTimeout(d);d=a.a.setTimeout(function(){b(e)},
c)}})},rateLimit:function(a,c){var d,e,f;"number"==typeof c?d=c:(d=c.timeout,e=c.method);a.Hb=!1;f="function"==typeof e?e:"notifyWhenChangesStop"==e?Y:X;a.ub(function(a){return f(a,d,c)})},deferred:function(b,c){if(!0!==c)throw Error("The 'deferred' extender only accepts the value 'true', because it is not supported to turn deferral off once enabled.");b.Hb||(b.Hb=!0,b.ub(function(c){var e,f=!1;return function(){if(!f){a.na.cancel(e);e=a.na.zb(c);try{f=!0,b.notifySubscribers(n,"dirty")}finally{f=
!1}}}}))},notify:function(a,c){a.equalityComparer="always"==c?null:K}};var W={undefined:1,"boolean":1,number:1,string:1};a.b("extenders",a.Ta);a.ic=function(b,c,d){this.da=b;this.lc=c;this.mc=d;this.Ib=!1;this.fb=this.Jb=null;a.L(this,"dispose",this.s);a.L(this,"disposeWhenNodeIsRemoved",this.l)};a.ic.prototype.s=function(){this.Ib||(this.fb&&a.a.K.yb(this.Jb,this.fb),this.Ib=!0,this.mc(),this.da=this.lc=this.mc=this.Jb=this.fb=null)};a.ic.prototype.l=function(b){this.Jb=b;a.a.K.za(b,this.fb=this.s.bind(this))};
a.T=function(){a.a.Ab(this,D);D.qb(this)};var D={qb:function(a){a.U={change:[]};a.sc=1},subscribe:function(b,c,d){var e=this;d=d||"change";var f=new a.ic(e,c?b.bind(c):b,function(){a.a.Pa(e.U[d],f);e.hb&&e.hb(d)});e.Qa&&e.Qa(d);e.U[d]||(e.U[d]=[]);e.U[d].push(f);return f},notifySubscribers:function(b,c){c=c||"change";"change"===c&&this.Gb();if(this.Wa(c)){var d="change"===c&&this.ed||this.U[c].slice(0);try{a.u.xc();for(var e=0,f;f=d[e];++e)f.Ib||f.lc(b)}finally{a.u.end()}}},ob:function(){return this.sc},
Dd:function(a){return this.ob()!==a},Gb:function(){++this.sc},ub:function(b){var c=this,d=a.O(c),e,f,g,h,m;c.gb||(c.gb=c.notifySubscribers,c.notifySubscribers=Z);var k=b(function(){c.Ja=!1;d&&h===c&&(h=c.nc?c.nc():c());var a=f||m&&c.sb(g,h);m=f=e=!1;a&&c.gb(g=h)});c.qc=function(a,b){b&&c.Ja||(m=!b);c.ed=c.U.change.slice(0);c.Ja=e=!0;h=a;k()};c.pc=function(a){e||(g=a,c.gb(a,"beforeChange"))};c.rc=function(){m=!0};c.gd=function(){c.sb(g,c.v(!0))&&(f=!0)}},Wa:function(a){return this.U[a]&&this.U[a].length},
Bd:function(b){if(b)return this.U[b]&&this.U[b].length||0;var c=0;a.a.P(this.U,function(a,b){"dirty"!==a&&(c+=b.length)});return c},sb:function(a,c){return!this.equalityComparer||!this.equalityComparer(a,c)},toString:function(){return"[object Object]"},extend:function(b){var c=this;b&&a.a.P(b,function(b,e){var f=a.Ta[b];"function"==typeof f&&(c=f(c,e)||c)});return c}};a.L(D,"init",D.qb);a.L(D,"subscribe",D.subscribe);a.L(D,"extend",D.extend);a.L(D,"getSubscriptionsCount",D.Bd);a.a.Ba&&a.a.setPrototypeOf(D,
Function.prototype);a.T.fn=D;a.Qc=function(a){return null!=a&&"function"==typeof a.subscribe&&"function"==typeof a.notifySubscribers};a.b("subscribable",a.T);a.b("isSubscribable",a.Qc);a.S=a.u=function(){function b(a){d.push(e);e=a}function c(){e=d.pop()}var d=[],e,f=0;return{xc:b,end:c,cc:function(b){if(e){if(!a.Qc(b))throw Error("Only subscribable things can act as dependencies");e.od.call(e.pd,b,b.fd||(b.fd=++f))}},G:function(a,d,e){try{return b(),a.apply(d,e||[])}finally{c()}},qa:function(){if(e)return e.o.qa()},
Va:function(){if(e)return e.o.Va()},Ya:function(){if(e)return e.Ya},o:function(){if(e)return e.o}}}();a.b("computedContext",a.S);a.b("computedContext.getDependenciesCount",a.S.qa);a.b("computedContext.getDependencies",a.S.Va);a.b("computedContext.isInitial",a.S.Ya);a.b("computedContext.registerDependency",a.S.cc);a.b("ignoreDependencies",a.Yd=a.u.G);var I=a.a.Da("_latestValue");a.ta=function(b){function c(){if(0<arguments.length)return c.sb(c[I],arguments[0])&&(c.ya(),c[I]=arguments[0],c.xa()),this;
a.u.cc(c);return c[I]}c[I]=b;a.a.Ba||a.a.extend(c,a.T.fn);a.T.fn.qb(c);a.a.Ab(c,F);a.options.deferUpdates&&a.Ta.deferred(c,!0);return c};var F={equalityComparer:K,v:function(){return this[I]},xa:function(){this.notifySubscribers(this[I],"spectate");this.notifySubscribers(this[I])},ya:function(){this.notifySubscribers(this[I],"beforeChange")}};a.a.Ba&&a.a.setPrototypeOf(F,a.T.fn);var G=a.ta.Ma="__ko_proto__";F[G]=a.ta;a.O=function(b){if((b="function"==typeof b&&b[G])&&b!==F[G]&&b!==a.o.fn[G])throw Error("Invalid object that looks like an observable; possibly from another Knockout instance");
return!!b};a.Za=function(b){return"function"==typeof b&&(b[G]===F[G]||b[G]===a.o.fn[G]&&b.Nc)};a.b("observable",a.ta);a.b("isObservable",a.O);a.b("isWriteableObservable",a.Za);a.b("isWritableObservable",a.Za);a.b("observable.fn",F);a.L(F,"peek",F.v);a.L(F,"valueHasMutated",F.xa);a.L(F,"valueWillMutate",F.ya);a.Ha=function(b){b=b||[];if("object"!=typeof b||!("length"in b))throw Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");b=a.ta(b);a.a.Ab(b,
a.Ha.fn);return b.extend({trackArrayChanges:!0})};a.Ha.fn={remove:function(b){for(var c=this.v(),d=[],e="function"!=typeof b||a.O(b)?function(a){return a===b}:b,f=0;f<c.length;f++){var g=c[f];if(e(g)){0===d.length&&this.ya();if(c[f]!==g)throw Error("Array modified during remove; cannot remove item");d.push(g);c.splice(f,1);f--}}d.length&&this.xa();return d},removeAll:function(b){if(b===n){var c=this.v(),d=c.slice(0);this.ya();c.splice(0,c.length);this.xa();return d}return b?this.remove(function(c){return 0<=
a.a.A(b,c)}):[]},destroy:function(b){var c=this.v(),d="function"!=typeof b||a.O(b)?function(a){return a===b}:b;this.ya();for(var e=c.length-1;0<=e;e--){var f=c[e];d(f)&&(f._destroy=!0)}this.xa()},destroyAll:function(b){return b===n?this.destroy(function(){return!0}):b?this.destroy(function(c){return 0<=a.a.A(b,c)}):[]},indexOf:function(b){var c=this();return a.a.A(c,b)},replace:function(a,c){var d=this.indexOf(a);0<=d&&(this.ya(),this.v()[d]=c,this.xa())},sorted:function(a){var c=this().slice(0);
return a?c.sort(a):c.sort()},reversed:function(){return this().slice(0).reverse()}};a.a.Ba&&a.a.setPrototypeOf(a.Ha.fn,a.ta.fn);a.a.D("pop push reverse shift sort splice unshift".split(" "),function(b){a.Ha.fn[b]=function(){var a=this.v();this.ya();this.zc(a,b,arguments);var d=a[b].apply(a,arguments);this.xa();return d===a?this:d}});a.a.D(["slice"],function(b){a.Ha.fn[b]=function(){var a=this();return a[b].apply(a,arguments)}});a.Pc=function(b){return a.O(b)&&"function"==typeof b.remove&&"function"==
typeof b.push};a.b("observableArray",a.Ha);a.b("isObservableArray",a.Pc);a.Ta.trackArrayChanges=function(b,c){function d(){function c(){if(m){var d=[].concat(b.v()||[]),e;if(b.Wa("arrayChange")){if(!f||1<m)f=a.a.Pb(k,d,b.Ob);e=f}k=d;f=null;m=0;e&&e.length&&b.notifySubscribers(e,"arrayChange")}}e?c():(e=!0,h=b.subscribe(function(){++m},null,"spectate"),k=[].concat(b.v()||[]),f=null,g=b.subscribe(c))}b.Ob={};c&&"object"==typeof c&&a.a.extend(b.Ob,c);b.Ob.sparse=!0;if(!b.zc){var e=!1,f=null,g,h,m=0,
k,l=b.Qa,p=b.hb;b.Qa=function(a){l&&l.call(b,a);"arrayChange"===a&&d()};b.hb=function(a){p&&p.call(b,a);"arrayChange"!==a||b.Wa("arrayChange")||(g&&g.s(),h&&h.s(),h=g=null,e=!1,k=n)};b.zc=function(b,c,d){function l(a,b,c){return k[k.length]={status:a,value:b,index:c}}if(e&&!m){var k=[],p=b.length,g=d.length,h=0;switch(c){case "push":h=p;case "unshift":for(c=0;c<g;c++)l("added",d[c],h+c);break;case "pop":h=p-1;case "shift":p&&l("deleted",b[h],h);break;case "splice":c=Math.min(Math.max(0,0>d[0]?p+d[0]:
d[0]),p);for(var p=1===g?p:Math.min(c+(d[1]||0),p),g=c+g-2,h=Math.max(p,g),U=[],L=[],n=2;c<h;++c,++n)c<p&&L.push(l("deleted",b[c],c)),c<g&&U.push(l("added",d[n],c));a.a.Kc(L,U);break;default:return}f=k}}}};var r=a.a.Da("_state");a.o=a.$=function(b,c,d){function e(){if(0<arguments.length){if("function"===typeof f)f.apply(g.nb,arguments);else throw Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");return this}g.ra||
a.u.cc(e);(g.ka||g.J&&e.Xa())&&e.ha();return g.X}"object"===typeof b?d=b:(d=d||{},b&&(d.read=b));if("function"!=typeof d.read)throw Error("Pass a function that returns the value of the ko.computed");var f=d.write,g={X:n,sa:!0,ka:!0,rb:!1,jc:!1,ra:!1,wb:!1,J:!1,Wc:d.read,nb:c||d.owner,l:d.disposeWhenNodeIsRemoved||d.l||null,Sa:d.disposeWhen||d.Sa,Rb:null,I:{},V:0,Ic:null};e[r]=g;e.Nc="function"===typeof f;a.a.Ba||a.a.extend(e,a.T.fn);a.T.fn.qb(e);a.a.Ab(e,C);d.pure?(g.wb=!0,g.J=!0,a.a.extend(e,da)):
d.deferEvaluation&&a.a.extend(e,ea);a.options.deferUpdates&&a.Ta.deferred(e,!0);g.l&&(g.jc=!0,g.l.nodeType||(g.l=null));g.J||d.deferEvaluation||e.ha();g.l&&e.ja()&&a.a.K.za(g.l,g.Rb=function(){e.s()});return e};var C={equalityComparer:K,qa:function(){return this[r].V},Va:function(){var b=[];a.a.P(this[r].I,function(a,d){b[d.Ka]=d.da});return b},Vb:function(b){if(!this[r].V)return!1;var c=this.Va();return-1!==a.a.A(c,b)?!0:!!a.a.Lb(c,function(a){return a.Vb&&a.Vb(b)})},uc:function(a,c,d){if(this[r].wb&&
c===this)throw Error("A 'pure' computed must not be called recursively");this[r].I[a]=d;d.Ka=this[r].V++;d.La=c.ob()},Xa:function(){var a,c,d=this[r].I;for(a in d)if(Object.prototype.hasOwnProperty.call(d,a)&&(c=d[a],this.Ia&&c.da.Ja||c.da.Dd(c.La)))return!0},Jd:function(){this.Ia&&!this[r].rb&&this.Ia(!1)},ja:function(){var a=this[r];return a.ka||0<a.V},Rd:function(){this.Ja?this[r].ka&&(this[r].sa=!0):this.Hc()},$c:function(a){if(a.Hb){var c=a.subscribe(this.Jd,this,"dirty"),d=a.subscribe(this.Rd,
this);return{da:a,s:function(){c.s();d.s()}}}return a.subscribe(this.Hc,this)},Hc:function(){var b=this,c=b.throttleEvaluation;c&&0<=c?(clearTimeout(this[r].Ic),this[r].Ic=a.a.setTimeout(function(){b.ha(!0)},c)):b.Ia?b.Ia(!0):b.ha(!0)},ha:function(b){var c=this[r],d=c.Sa,e=!1;if(!c.rb&&!c.ra){if(c.l&&!a.a.Sb(c.l)||d&&d()){if(!c.jc){this.s();return}}else c.jc=!1;c.rb=!0;try{e=this.zd(b)}finally{c.rb=!1}return e}},zd:function(b){var c=this[r],d=!1,e=c.wb?n:!c.V,d={qd:this,mb:c.I,Qb:c.V};a.u.xc({pd:d,
od:ba,o:this,Ya:e});c.I={};c.V=0;var f=this.yd(c,d);c.V?d=this.sb(c.X,f):(this.s(),d=!0);d&&(c.J?this.Gb():this.notifySubscribers(c.X,"beforeChange"),c.X=f,this.notifySubscribers(c.X,"spectate"),!c.J&&b&&this.notifySubscribers(c.X),this.rc&&this.rc());e&&this.notifySubscribers(c.X,"awake");return d},yd:function(b,c){try{var d=b.Wc;return b.nb?d.call(b.nb):d()}finally{a.u.end(),c.Qb&&!b.J&&a.a.P(c.mb,aa),b.sa=b.ka=!1}},v:function(a){var c=this[r];(c.ka&&(a||!c.V)||c.J&&this.Xa())&&this.ha();return c.X},
ub:function(b){a.T.fn.ub.call(this,b);this.nc=function(){this[r].J||(this[r].sa?this.ha():this[r].ka=!1);return this[r].X};this.Ia=function(a){this.pc(this[r].X);this[r].ka=!0;a&&(this[r].sa=!0);this.qc(this,!a)}},s:function(){var b=this[r];!b.J&&b.I&&a.a.P(b.I,function(a,b){b.s&&b.s()});b.l&&b.Rb&&a.a.K.yb(b.l,b.Rb);b.I=n;b.V=0;b.ra=!0;b.sa=!1;b.ka=!1;b.J=!1;b.l=n;b.Sa=n;b.Wc=n;this.Nc||(b.nb=n)}},da={Qa:function(b){var c=this,d=c[r];if(!d.ra&&d.J&&"change"==b){d.J=!1;if(d.sa||c.Xa())d.I=null,d.V=
0,c.ha()&&c.Gb();else{var e=[];a.a.P(d.I,function(a,b){e[b.Ka]=a});a.a.D(e,function(a,b){var e=d.I[a],m=c.$c(e.da);m.Ka=b;m.La=e.La;d.I[a]=m});c.Xa()&&c.ha()&&c.Gb()}d.ra||c.notifySubscribers(d.X,"awake")}},hb:function(b){var c=this[r];c.ra||"change"!=b||this.Wa("change")||(a.a.P(c.I,function(a,b){b.s&&(c.I[a]={da:b.da,Ka:b.Ka,La:b.La},b.s())}),c.J=!0,this.notifySubscribers(n,"asleep"))},ob:function(){var b=this[r];b.J&&(b.sa||this.Xa())&&this.ha();return a.T.fn.ob.call(this)}},ea={Qa:function(a){"change"!=
a&&"beforeChange"!=a||this.v()}};a.a.Ba&&a.a.setPrototypeOf(C,a.T.fn);var N=a.ta.Ma;C[N]=a.o;a.Oc=function(a){return"function"==typeof a&&a[N]===C[N]};a.Fd=function(b){return a.Oc(b)&&b[r]&&b[r].wb};a.b("computed",a.o);a.b("dependentObservable",a.o);a.b("isComputed",a.Oc);a.b("isPureComputed",a.Fd);a.b("computed.fn",C);a.L(C,"peek",C.v);a.L(C,"dispose",C.s);a.L(C,"isActive",C.ja);a.L(C,"getDependenciesCount",C.qa);a.L(C,"getDependencies",C.Va);a.xb=function(b,c){if("function"===typeof b)return a.o(b,
c,{pure:!0});b=a.a.extend({},b);b.pure=!0;return a.o(b,c)};a.b("pureComputed",a.xb);(function(){function b(a,f,g){g=g||new d;a=f(a);if("object"!=typeof a||null===a||a===n||a instanceof RegExp||a instanceof Date||a instanceof String||a instanceof Number||a instanceof Boolean)return a;var h=a instanceof Array?[]:{};g.save(a,h);c(a,function(c){var d=f(a[c]);switch(typeof d){case "boolean":case "number":case "string":case "function":h[c]=d;break;case "object":case "undefined":var l=g.get(d);h[c]=l!==
n?l:b(d,f,g)}});return h}function c(a,b){if(a instanceof Array){for(var c=0;c<a.length;c++)b(c);"function"==typeof a.toJSON&&b("toJSON")}else for(c in a)b(c)}function d(){this.keys=[];this.values=[]}a.ad=function(c){if(0==arguments.length)throw Error("When calling ko.toJS, pass the object you want to convert.");return b(c,function(b){for(var c=0;a.O(b)&&10>c;c++)b=b();return b})};a.toJSON=function(b,c,d){b=a.ad(b);return a.a.hc(b,c,d)};d.prototype={constructor:d,save:function(b,c){var d=a.a.A(this.keys,
b);0<=d?this.values[d]=c:(this.keys.push(b),this.values.push(c))},get:function(b){b=a.a.A(this.keys,b);return 0<=b?this.values[b]:n}}})();a.b("toJS",a.ad);a.b("toJSON",a.toJSON);a.Wd=function(b,c,d){function e(c){var e=a.xb(b,d).extend({ma:"always"}),h=e.subscribe(function(a){a&&(h.s(),c(a))});e.notifySubscribers(e.v());return h}return"function"!==typeof Promise||c?e(c.bind(d)):new Promise(e)};a.b("when",a.Wd);(function(){a.w={M:function(b){switch(a.a.R(b)){case "option":return!0===b.__ko__hasDomDataOptionValue__?
a.a.g.get(b,a.c.options.$b):7>=a.a.W?b.getAttributeNode("value")&&b.getAttributeNode("value").specified?b.value:b.text:b.value;case "select":return 0<=b.selectedIndex?a.w.M(b.options[b.selectedIndex]):n;default:return b.value}},cb:function(b,c,d){switch(a.a.R(b)){case "option":"string"===typeof c?(a.a.g.set(b,a.c.options.$b,n),"__ko__hasDomDataOptionValue__"in b&&delete b.__ko__hasDomDataOptionValue__,b.value=c):(a.a.g.set(b,a.c.options.$b,c),b.__ko__hasDomDataOptionValue__=!0,b.value="number"===
typeof c?c:"");break;case "select":if(""===c||null===c)c=n;for(var e=-1,f=0,g=b.options.length,h;f<g;++f)if(h=a.w.M(b.options[f]),h==c||""===h&&c===n){e=f;break}if(d||0<=e||c===n&&1<b.size)b.selectedIndex=e,6===a.a.W&&a.a.setTimeout(function(){b.selectedIndex=e},0);break;default:if(null===c||c===n)c="";b.value=c}}}})();a.b("selectExtensions",a.w);a.b("selectExtensions.readValue",a.w.M);a.b("selectExtensions.writeValue",a.w.cb);a.m=function(){function b(b){b=a.a.Db(b);123===b.charCodeAt(0)&&(b=b.slice(1,
-1));b+="\n,";var c=[],d=b.match(e),p,q=[],h=0;if(1<d.length){for(var x=0,B;B=d[x];++x){var u=B.charCodeAt(0);if(44===u){if(0>=h){c.push(p&&q.length?{key:p,value:q.join("")}:{unknown:p||q.join("")});p=h=0;q=[];continue}}else if(58===u){if(!h&&!p&&1===q.length){p=q.pop();continue}}else if(47===u&&1<B.length&&(47===B.charCodeAt(1)||42===B.charCodeAt(1)))continue;else 47===u&&x&&1<B.length?(u=d[x-1].match(f))&&!g[u[0]]&&(b=b.substr(b.indexOf(B)+1),d=b.match(e),x=-1,B="/"):40===u||123===u||91===u?++h:
41===u||125===u||93===u?--h:p||q.length||34!==u&&39!==u||(B=B.slice(1,-1));q.push(B)}if(0<h)throw Error("Unbalanced parentheses, braces, or brackets");}return c}var c=["true","false","null","undefined"],d=/^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i,e=RegExp("\"(?:\\\\.|[^\"])*\"|'(?:\\\\.|[^'])*'|`(?:\\\\.|[^`])*`|/\\*(?:[^*]|\\*+[^*/])*\\*+/|//.*\n|/(?:\\\\.|[^/])+/w*|[^\\s:,/][^,\"'`{}()/:[\\]]*[^\\s,\"'`{}()/:[\\]]|[^\\s]","g"),f=/[\])"'A-Za-z0-9_$]+$/,g={"in":1,"return":1,"typeof":1},
h={};return{Ra:[],wa:h,ac:b,vb:function(e,f){function l(b,e){var f;if(!x){var k=a.getBindingHandler(b);if(k&&k.preprocess&&!(e=k.preprocess(e,b,l)))return;if(k=h[b])f=e,0<=a.a.A(c,f)?f=!1:(k=f.match(d),f=null===k?!1:k[1]?"Object("+k[1]+")"+k[2]:f),k=f;k&&q.push("'"+("string"==typeof h[b]?h[b]:b)+"':function(_z){"+f+"=_z}")}g&&(e="function(){return "+e+" }");p.push("'"+b+"':"+e)}f=f||{};var p=[],q=[],g=f.valueAccessors,x=f.bindingParams,B="string"===typeof e?b(e):e;a.a.D(B,function(a){l(a.key||a.unknown,
a.value)});q.length&&l("_ko_property_writers","{"+q.join(",")+" }");return p.join(",")},Id:function(a,b){for(var c=0;c<a.length;c++)if(a[c].key==b)return!0;return!1},eb:function(b,c,d,e,f){if(b&&a.O(b))!a.Za(b)||f&&b.v()===e||b(e);else if((b=c.get("_ko_property_writers"))&&b[d])b[d](e)}}}();a.b("expressionRewriting",a.m);a.b("expressionRewriting.bindingRewriteValidators",a.m.Ra);a.b("expressionRewriting.parseObjectLiteral",a.m.ac);a.b("expressionRewriting.preProcessBindings",a.m.vb);a.b("expressionRewriting._twoWayBindings",
a.m.wa);a.b("jsonExpressionRewriting",a.m);a.b("jsonExpressionRewriting.insertPropertyAccessorsIntoJson",a.m.vb);(function(){function b(a){return 8==a.nodeType&&g.test(f?a.text:a.nodeValue)}function c(a){return 8==a.nodeType&&h.test(f?a.text:a.nodeValue)}function d(d,e){for(var f=d,h=1,g=[];f=f.nextSibling;){if(c(f)&&(a.a.g.set(f,k,!0),h--,0===h))return g;g.push(f);b(f)&&h++}if(!e)throw Error("Cannot find closing comment tag to match: "+d.nodeValue);return null}function e(a,b){var c=d(a,b);return c?
0<c.length?c[c.length-1].nextSibling:a.nextSibling:null}var f=w&&"\x3c!--test--\x3e"===w.createComment("test").text,g=f?/^\x3c!--\s*ko(?:\s+([\s\S]+))?\s*--\x3e$/:/^\s*ko(?:\s+([\s\S]+))?\s*$/,h=f?/^\x3c!--\s*\/ko\s*--\x3e$/:/^\s*\/ko\s*$/,m={ul:!0,ol:!0},k="__ko_matchedEndComment__";a.h={ea:{},childNodes:function(a){return b(a)?d(a):a.childNodes},Ea:function(c){if(b(c)){c=a.h.childNodes(c);for(var d=0,e=c.length;d<e;d++)a.removeNode(c[d])}else a.a.Tb(c)},va:function(c,d){if(b(c)){a.h.Ea(c);for(var e=
c.nextSibling,f=0,k=d.length;f<k;f++)e.parentNode.insertBefore(d[f],e)}else a.a.va(c,d)},Vc:function(a,c){var d;b(a)?(d=a.nextSibling,a=a.parentNode):d=a.firstChild;d?c!==d&&a.insertBefore(c,d):a.appendChild(c)},Wb:function(c,d,e){e?(e=e.nextSibling,b(c)&&(c=c.parentNode),e?d!==e&&c.insertBefore(d,e):c.appendChild(d)):a.h.Vc(c,d)},firstChild:function(a){if(b(a))return!a.nextSibling||c(a.nextSibling)?null:a.nextSibling;if(a.firstChild&&c(a.firstChild))throw Error("Found invalid end comment, as the first child of "+
a);return a.firstChild},nextSibling:function(d){b(d)&&(d=e(d));if(d.nextSibling&&c(d.nextSibling)){var f=d.nextSibling;if(c(f)&&!a.a.g.get(f,k))throw Error("Found end comment without a matching opening comment, as child of "+d);return null}return d.nextSibling},Cd:b,Vd:function(a){return(a=(f?a.text:a.nodeValue).match(g))?a[1]:null},Sc:function(d){if(m[a.a.R(d)]){var f=d.firstChild;if(f){do if(1===f.nodeType){var k;k=f.firstChild;var h=null;if(k){do if(h)h.push(k);else if(b(k)){var g=e(k,!0);g?k=
g:h=[k]}else c(k)&&(h=[k]);while(k=k.nextSibling)}if(k=h)for(h=f.nextSibling,g=0;g<k.length;g++)h?d.insertBefore(k[g],h):d.appendChild(k[g])}while(f=f.nextSibling)}}}}})();a.b("virtualElements",a.h);a.b("virtualElements.allowedBindings",a.h.ea);a.b("virtualElements.emptyNode",a.h.Ea);a.b("virtualElements.insertAfter",a.h.Wb);a.b("virtualElements.prepend",a.h.Vc);a.b("virtualElements.setDomNodeChildren",a.h.va);(function(){a.ga=function(){this.nd={}};a.a.extend(a.ga.prototype,{nodeHasBindings:function(b){switch(b.nodeType){case 1:return null!=
b.getAttribute("data-bind")||a.j.getComponentNameForNode(b);case 8:return a.h.Cd(b);default:return!1}},getBindings:function(b,c){var d=this.getBindingsString(b,c),d=d?this.parseBindingsString(d,c,b):null;return a.j.tc(d,b,c,!1)},getBindingAccessors:function(b,c){var d=this.getBindingsString(b,c),d=d?this.parseBindingsString(d,c,b,{valueAccessors:!0}):null;return a.j.tc(d,b,c,!0)},getBindingsString:function(b){switch(b.nodeType){case 1:return b.getAttribute("data-bind");case 8:return a.h.Vd(b);default:return null}},
parseBindingsString:function(b,c,d,e){try{var f=this.nd,g=b+(e&&e.valueAccessors||""),h;if(!(h=f[g])){var m,k="with($context){with($data||{}){return{"+a.m.vb(b,e)+"}}}";m=new Function("$context","$element",k);h=f[g]=m}return h(c,d)}catch(l){throw l.message="Unable to parse bindings.\nBindings value: "+b+"\nMessage: "+l.message,l;}}});a.ga.instance=new a.ga})();a.b("bindingProvider",a.ga);(function(){function b(b){var c=(b=a.a.g.get(b,z))&&b.N;c&&(b.N=null,c.Tc())}function c(c,d,e){this.node=c;this.yc=
d;this.kb=[];this.H=!1;d.N||a.a.K.za(c,b);e&&e.N&&(e.N.kb.push(c),this.Kb=e)}function d(a){return function(){return a}}function e(a){return a()}function f(b){return a.a.Ga(a.u.G(b),function(a,c){return function(){return b()[c]}})}function g(b,c,e){return"function"===typeof b?f(b.bind(null,c,e)):a.a.Ga(b,d)}function h(a,b){return f(this.getBindings.bind(this,a,b))}function m(b,c){var d=a.h.firstChild(c);if(d){var e,f=a.ga.instance,l=f.preprocessNode;if(l){for(;e=d;)d=a.h.nextSibling(e),l.call(f,e);
d=a.h.firstChild(c)}for(;e=d;)d=a.h.nextSibling(e),k(b,e)}a.i.ma(c,a.i.H)}function k(b,c){var d=b,e=1===c.nodeType;e&&a.h.Sc(c);if(e||a.ga.instance.nodeHasBindings(c))d=p(c,null,b).bindingContextForDescendants;d&&!u[a.a.R(c)]&&m(d,c)}function l(b){var c=[],d={},e=[];a.a.P(b,function ca(f){if(!d[f]){var k=a.getBindingHandler(f);k&&(k.after&&(e.push(f),a.a.D(k.after,function(c){if(b[c]){if(-1!==a.a.A(e,c))throw Error("Cannot combine the following bindings, because they have a cyclic dependency: "+e.join(", "));
ca(c)}}),e.length--),c.push({key:f,Mc:k}));d[f]=!0}});return c}function p(b,c,d){var f=a.a.g.Ub(b,z,{}),k=f.hd;if(!c){if(k)throw Error("You cannot apply bindings multiple times to the same element.");f.hd=!0}k||(f.context=d);f.Zb||(f.Zb={});var g;if(c&&"function"!==typeof c)g=c;else{var p=a.ga.instance,q=p.getBindingAccessors||h,m=a.$(function(){if(g=c?c(d,b):q.call(p,b,d)){if(d[t])d[t]();if(d[B])d[B]()}return g},null,{l:b});g&&m.ja()||(m=null)}var x=d,u;if(g){var J=function(){return a.a.Ga(m?m():
g,e)},r=m?function(a){return function(){return e(m()[a])}}:function(a){return g[a]};J.get=function(a){return g[a]&&e(r(a))};J.has=function(a){return a in g};a.i.H in g&&a.i.subscribe(b,a.i.H,function(){var c=(0,g[a.i.H])();if(c){var d=a.h.childNodes(b);d.length&&c(d,a.Ec(d[0]))}});a.i.pa in g&&(x=a.i.Cb(b,d),a.i.subscribe(b,a.i.pa,function(){var c=(0,g[a.i.pa])();c&&a.h.firstChild(b)&&c(b)}));f=l(g);a.a.D(f,function(c){var d=c.Mc.init,e=c.Mc.update,f=c.key;if(8===b.nodeType&&!a.h.ea[f])throw Error("The binding '"+
f+"' cannot be used with virtual elements");try{"function"==typeof d&&a.u.G(function(){var a=d(b,r(f),J,x.$data,x);if(a&&a.controlsDescendantBindings){if(u!==n)throw Error("Multiple bindings ("+u+" and "+f+") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");u=f}}),"function"==typeof e&&a.$(function(){e(b,r(f),J,x.$data,x)},null,{l:b})}catch(k){throw k.message='Unable to process binding "'+f+": "+g[f]+'"\nMessage: '+k.message,
k;}})}f=u===n;return{shouldBindDescendants:f,bindingContextForDescendants:f&&x}}function q(b,c){return b&&b instanceof a.fa?b:new a.fa(b,n,n,c)}var t=a.a.Da("_subscribable"),x=a.a.Da("_ancestorBindingInfo"),B=a.a.Da("_dataDependency");a.c={};var u={script:!0,textarea:!0,template:!0};a.getBindingHandler=function(b){return a.c[b]};var J={};a.fa=function(b,c,d,e,f){function k(){var b=p?h():h,f=a.a.f(b);c?(a.a.extend(l,c),x in c&&(l[x]=c[x])):(l.$parents=[],l.$root=f,l.ko=a);l[t]=q;g?f=l.$data:(l.$rawData=
b,l.$data=f);d&&(l[d]=f);e&&e(l,c,f);if(c&&c[t]&&!a.S.o().Vb(c[t]))c[t]();m&&(l[B]=m);return l.$data}var l=this,g=b===J,h=g?n:b,p="function"==typeof h&&!a.O(h),q,m=f&&f.dataDependency;f&&f.exportDependencies?k():(q=a.xb(k),q.v(),q.ja()?q.equalityComparer=null:l[t]=n)};a.fa.prototype.createChildContext=function(b,c,d,e){!e&&c&&"object"==typeof c&&(e=c,c=e.as,d=e.extend);if(c&&e&&e.noChildContext){var f="function"==typeof b&&!a.O(b);return new a.fa(J,this,null,function(a){d&&d(a);a[c]=f?b():b},e)}return new a.fa(b,
this,c,function(a,b){a.$parentContext=b;a.$parent=b.$data;a.$parents=(b.$parents||[]).slice(0);a.$parents.unshift(a.$parent);d&&d(a)},e)};a.fa.prototype.extend=function(b,c){return new a.fa(J,this,null,function(c){a.a.extend(c,"function"==typeof b?b(c):b)},c)};var z=a.a.g.Z();c.prototype.Tc=function(){this.Kb&&this.Kb.N&&this.Kb.N.sd(this.node)};c.prototype.sd=function(b){a.a.Pa(this.kb,b);!this.kb.length&&this.H&&this.Cc()};c.prototype.Cc=function(){this.H=!0;this.yc.N&&!this.kb.length&&(this.yc.N=
null,a.a.K.yb(this.node,b),a.i.ma(this.node,a.i.pa),this.Tc())};a.i={H:"childrenComplete",pa:"descendantsComplete",subscribe:function(b,c,d,e,f){var k=a.a.g.Ub(b,z,{});k.Fa||(k.Fa=new a.T);f&&f.notifyImmediately&&k.Zb[c]&&a.u.G(d,e,[b]);return k.Fa.subscribe(d,e,c)},ma:function(b,c){var d=a.a.g.get(b,z);if(d&&(d.Zb[c]=!0,d.Fa&&d.Fa.notifySubscribers(b,c),c==a.i.H))if(d.N)d.N.Cc();else if(d.N===n&&d.Fa&&d.Fa.Wa(a.i.pa))throw Error("descendantsComplete event not supported for bindings on this node");
},Cb:function(b,d){var e=a.a.g.Ub(b,z,{});e.N||(e.N=new c(b,e,d[x]));return d[x]==e?d:d.extend(function(a){a[x]=e})}};a.Td=function(b){return(b=a.a.g.get(b,z))&&b.context};a.ib=function(b,c,d){1===b.nodeType&&a.h.Sc(b);return p(b,c,q(d))};a.ld=function(b,c,d){d=q(d);return a.ib(b,g(c,d,b),d)};a.Oa=function(a,b){1!==b.nodeType&&8!==b.nodeType||m(q(a),b)};a.vc=function(a,b,c){!v&&A.jQuery&&(v=A.jQuery);if(2>arguments.length){if(b=w.body,!b)throw Error("ko.applyBindings: could not find document.body; has the document been loaded?");
}else if(!b||1!==b.nodeType&&8!==b.nodeType)throw Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");k(q(a,c),b)};a.Dc=function(b){return!b||1!==b.nodeType&&8!==b.nodeType?n:a.Td(b)};a.Ec=function(b){return(b=a.Dc(b))?b.$data:n};a.b("bindingHandlers",a.c);a.b("bindingEvent",a.i);a.b("bindingEvent.subscribe",a.i.subscribe);a.b("bindingEvent.startPossiblyAsyncContentBinding",a.i.Cb);a.b("applyBindings",a.vc);a.b("applyBindingsToDescendants",a.Oa);
a.b("applyBindingAccessorsToNode",a.ib);a.b("applyBindingsToNode",a.ld);a.b("contextFor",a.Dc);a.b("dataFor",a.Ec)})();(function(b){function c(c,e){var k=Object.prototype.hasOwnProperty.call(f,c)?f[c]:b,l;k?k.subscribe(e):(k=f[c]=new a.T,k.subscribe(e),d(c,function(b,d){var e=!(!d||!d.synchronous);g[c]={definition:b,Gd:e};delete f[c];l||e?k.notifySubscribers(b):a.na.zb(function(){k.notifySubscribers(b)})}),l=!0)}function d(a,b){e("getConfig",[a],function(c){c?e("loadComponent",[a,c],function(a){b(a,
c)}):b(null,null)})}function e(c,d,f,l){l||(l=a.j.loaders.slice(0));var g=l.shift();if(g){var q=g[c];if(q){var t=!1;if(q.apply(g,d.concat(function(a){t?f(null):null!==a?f(a):e(c,d,f,l)}))!==b&&(t=!0,!g.suppressLoaderExceptions))throw Error("Component loaders must supply values by invoking the callback, not by returning values synchronously.");}else e(c,d,f,l)}else f(null)}var f={},g={};a.j={get:function(d,e){var f=Object.prototype.hasOwnProperty.call(g,d)?g[d]:b;f?f.Gd?a.u.G(function(){e(f.definition)}):
a.na.zb(function(){e(f.definition)}):c(d,e)},Bc:function(a){delete g[a]},oc:e};a.j.loaders=[];a.b("components",a.j);a.b("components.get",a.j.get);a.b("components.clearCachedDefinition",a.j.Bc)})();(function(){function b(b,c,d,e){function g(){0===--B&&e(h)}var h={},B=2,u=d.template;d=d.viewModel;u?f(c,u,function(c){a.j.oc("loadTemplate",[b,c],function(a){h.template=a;g()})}):g();d?f(c,d,function(c){a.j.oc("loadViewModel",[b,c],function(a){h[m]=a;g()})}):g()}function c(a,b,d){if("function"===typeof b)d(function(a){return new b(a)});
else if("function"===typeof b[m])d(b[m]);else if("instance"in b){var e=b.instance;d(function(){return e})}else"viewModel"in b?c(a,b.viewModel,d):a("Unknown viewModel value: "+b)}function d(b){switch(a.a.R(b)){case "script":return a.a.ua(b.text);case "textarea":return a.a.ua(b.value);case "template":if(e(b.content))return a.a.Ca(b.content.childNodes)}return a.a.Ca(b.childNodes)}function e(a){return A.DocumentFragment?a instanceof DocumentFragment:a&&11===a.nodeType}function f(a,b,c){"string"===typeof b.require?
T||A.require?(T||A.require)([b.require],function(a){a&&"object"===typeof a&&a.Xd&&a["default"]&&(a=a["default"]);c(a)}):a("Uses require, but no AMD loader is present"):c(b)}function g(a){return function(b){throw Error("Component '"+a+"': "+b);}}var h={};a.j.register=function(b,c){if(!c)throw Error("Invalid configuration for "+b);if(a.j.tb(b))throw Error("Component "+b+" is already registered");h[b]=c};a.j.tb=function(a){return Object.prototype.hasOwnProperty.call(h,a)};a.j.unregister=function(b){delete h[b];
a.j.Bc(b)};a.j.Fc={getConfig:function(b,c){c(a.j.tb(b)?h[b]:null)},loadComponent:function(a,c,d){var e=g(a);f(e,c,function(c){b(a,e,c,d)})},loadTemplate:function(b,c,f){b=g(b);if("string"===typeof c)f(a.a.ua(c));else if(c instanceof Array)f(c);else if(e(c))f(a.a.la(c.childNodes));else if(c.element)if(c=c.element,A.HTMLElement?c instanceof HTMLElement:c&&c.tagName&&1===c.nodeType)f(d(c));else if("string"===typeof c){var h=w.getElementById(c);h?f(d(h)):b("Cannot find element with ID "+c)}else b("Unknown element type: "+
c);else b("Unknown template value: "+c)},loadViewModel:function(a,b,d){c(g(a),b,d)}};var m="createViewModel";a.b("components.register",a.j.register);a.b("components.isRegistered",a.j.tb);a.b("components.unregister",a.j.unregister);a.b("components.defaultLoader",a.j.Fc);a.j.loaders.push(a.j.Fc);a.j.dd=h})();(function(){function b(b,e){var f=b.getAttribute("params");if(f){var f=c.parseBindingsString(f,e,b,{valueAccessors:!0,bindingParams:!0}),f=a.a.Ga(f,function(c){return a.o(c,null,{l:b})}),g=a.a.Ga(f,
function(c){var e=c.v();return c.ja()?a.o({read:function(){return a.a.f(c())},write:a.Za(e)&&function(a){c()(a)},l:b}):e});Object.prototype.hasOwnProperty.call(g,"$raw")||(g.$raw=f);return g}return{$raw:{}}}a.j.getComponentNameForNode=function(b){var c=a.a.R(b);if(a.j.tb(c)&&(-1!=c.indexOf("-")||"[object HTMLUnknownElement]"==""+b||8>=a.a.W&&b.tagName===c))return c};a.j.tc=function(c,e,f,g){if(1===e.nodeType){var h=a.j.getComponentNameForNode(e);if(h){c=c||{};if(c.component)throw Error('Cannot use the "component" binding on a custom element matching a component');
var m={name:h,params:b(e,f)};c.component=g?function(){return m}:m}}return c};var c=new a.ga;9>a.a.W&&(a.j.register=function(a){return function(b){return a.apply(this,arguments)}}(a.j.register),w.createDocumentFragment=function(b){return function(){var c=b(),f=a.j.dd,g;for(g in f);return c}}(w.createDocumentFragment))})();(function(){function b(b,c,d){c=c.template;if(!c)throw Error("Component '"+b+"' has no template");b=a.a.Ca(c);a.h.va(d,b)}function c(a,b,c){var d=a.createViewModel;return d?d.call(a,
b,c):b}var d=0;a.c.component={init:function(e,f,g,h,m){function k(){var a=l&&l.dispose;"function"===typeof a&&a.call(l);q&&q.s();p=l=q=null}var l,p,q,t=a.a.la(a.h.childNodes(e));a.h.Ea(e);a.a.K.za(e,k);a.o(function(){var g=a.a.f(f()),h,u;"string"===typeof g?h=g:(h=a.a.f(g.name),u=a.a.f(g.params));if(!h)throw Error("No component name specified");var n=a.i.Cb(e,m),z=p=++d;a.j.get(h,function(d){if(p===z){k();if(!d)throw Error("Unknown component '"+h+"'");b(h,d,e);var f=c(d,u,{element:e,templateNodes:t});
d=n.createChildContext(f,{extend:function(a){a.$component=f;a.$componentTemplateNodes=t}});f&&f.koDescendantsComplete&&(q=a.i.subscribe(e,a.i.pa,f.koDescendantsComplete,f));l=f;a.Oa(d,e)}})},null,{l:e});return{controlsDescendantBindings:!0}}};a.h.ea.component=!0})();var V={"class":"className","for":"htmlFor"};a.c.attr={update:function(b,c){var d=a.a.f(c())||{};a.a.P(d,function(c,d){d=a.a.f(d);var g=c.indexOf(":"),g="lookupNamespaceURI"in b&&0<g&&b.lookupNamespaceURI(c.substr(0,g)),h=!1===d||null===
d||d===n;h?g?b.removeAttributeNS(g,c):b.removeAttribute(c):d=d.toString();8>=a.a.W&&c in V?(c=V[c],h?b.removeAttribute(c):b[c]=d):h||(g?b.setAttributeNS(g,c,d):b.setAttribute(c,d));"name"===c&&a.a.Yc(b,h?"":d)})}};(function(){a.c.checked={after:["value","attr"],init:function(b,c,d){function e(){var e=b.checked,f=g();if(!a.S.Ya()&&(e||!m&&!a.S.qa())){var k=a.u.G(c);if(l){var q=p?k.v():k,z=t;t=f;z!==f?e&&(a.a.Na(q,f,!0),a.a.Na(q,z,!1)):a.a.Na(q,f,e);p&&a.Za(k)&&k(q)}else h&&(f===n?f=e:e||(f=n)),a.m.eb(k,
d,"checked",f,!0)}}function f(){var d=a.a.f(c()),e=g();l?(b.checked=0<=a.a.A(d,e),t=e):b.checked=h&&e===n?!!d:g()===d}var g=a.xb(function(){if(d.has("checkedValue"))return a.a.f(d.get("checkedValue"));if(q)return d.has("value")?a.a.f(d.get("value")):b.value}),h="checkbox"==b.type,m="radio"==b.type;if(h||m){var k=c(),l=h&&a.a.f(k)instanceof Array,p=!(l&&k.push&&k.splice),q=m||l,t=l?g():n;m&&!b.name&&a.c.uniqueName.init(b,function(){return!0});a.o(e,null,{l:b});a.a.B(b,"click",e);a.o(f,null,{l:b});
k=n}}};a.m.wa.checked=!0;a.c.checkedValue={update:function(b,c){b.value=a.a.f(c())}}})();a.c["class"]={update:function(b,c){var d=a.a.Db(a.a.f(c()));a.a.Eb(b,b.__ko__cssValue,!1);b.__ko__cssValue=d;a.a.Eb(b,d,!0)}};a.c.css={update:function(b,c){var d=a.a.f(c());null!==d&&"object"==typeof d?a.a.P(d,function(c,d){d=a.a.f(d);a.a.Eb(b,c,d)}):a.c["class"].update(b,c)}};a.c.enable={update:function(b,c){var d=a.a.f(c());d&&b.disabled?b.removeAttribute("disabled"):d||b.disabled||(b.disabled=!0)}};a.c.disable=
{update:function(b,c){a.c.enable.update(b,function(){return!a.a.f(c())})}};a.c.event={init:function(b,c,d,e,f){var g=c()||{};a.a.P(g,function(g){"string"==typeof g&&a.a.B(b,g,function(b){var k,l=c()[g];if(l){try{var p=a.a.la(arguments);e=f.$data;p.unshift(e);k=l.apply(e,p)}finally{!0!==k&&(b.preventDefault?b.preventDefault():b.returnValue=!1)}!1===d.get(g+"Bubble")&&(b.cancelBubble=!0,b.stopPropagation&&b.stopPropagation())}})})}};a.c.foreach={Rc:function(b){return function(){var c=b(),d=a.a.bc(c);
if(!d||"number"==typeof d.length)return{foreach:c,templateEngine:a.ba.Ma};a.a.f(c);return{foreach:d.data,as:d.as,noChildContext:d.noChildContext,includeDestroyed:d.includeDestroyed,afterAdd:d.afterAdd,beforeRemove:d.beforeRemove,afterRender:d.afterRender,beforeMove:d.beforeMove,afterMove:d.afterMove,templateEngine:a.ba.Ma}}},init:function(b,c){return a.c.template.init(b,a.c.foreach.Rc(c))},update:function(b,c,d,e,f){return a.c.template.update(b,a.c.foreach.Rc(c),d,e,f)}};a.m.Ra.foreach=!1;a.h.ea.foreach=
!0;a.c.hasfocus={init:function(b,c,d){function e(e){b.__ko_hasfocusUpdating=!0;var f=b.ownerDocument;if("activeElement"in f){var g;try{g=f.activeElement}catch(l){g=f.body}e=g===b}f=c();a.m.eb(f,d,"hasfocus",e,!0);b.__ko_hasfocusLastValue=e;b.__ko_hasfocusUpdating=!1}var f=e.bind(null,!0),g=e.bind(null,!1);a.a.B(b,"focus",f);a.a.B(b,"focusin",f);a.a.B(b,"blur",g);a.a.B(b,"focusout",g);b.__ko_hasfocusLastValue=!1},update:function(b,c){var d=!!a.a.f(c());b.__ko_hasfocusUpdating||b.__ko_hasfocusLastValue===
d||(d?b.focus():b.blur(),!d&&b.__ko_hasfocusLastValue&&b.ownerDocument.body.focus(),a.u.G(a.a.Fb,null,[b,d?"focusin":"focusout"]))}};a.m.wa.hasfocus=!0;a.c.hasFocus=a.c.hasfocus;a.m.wa.hasFocus="hasfocus";a.c.html={init:function(){return{controlsDescendantBindings:!0}},update:function(b,c){a.a.fc(b,c())}};(function(){function b(b,d,e){a.c[b]={init:function(b,c,h,m,k){var l,p,q={},t,x,n;if(d){m=h.get("as");var u=h.get("noChildContext");n=!(m&&u);q={as:m,noChildContext:u,exportDependencies:n}}x=(t=
"render"==h.get("completeOn"))||h.has(a.i.pa);a.o(function(){var h=a.a.f(c()),m=!e!==!h,u=!p,r;if(n||m!==l){x&&(k=a.i.Cb(b,k));if(m){if(!d||n)q.dataDependency=a.S.o();r=d?k.createChildContext("function"==typeof h?h:c,q):a.S.qa()?k.extend(null,q):k}u&&a.S.qa()&&(p=a.a.Ca(a.h.childNodes(b),!0));m?(u||a.h.va(b,a.a.Ca(p)),a.Oa(r,b)):(a.h.Ea(b),t||a.i.ma(b,a.i.H));l=m}},null,{l:b});return{controlsDescendantBindings:!0}}};a.m.Ra[b]=!1;a.h.ea[b]=!0}b("if");b("ifnot",!1,!0);b("with",!0)})();a.c.let={init:function(b,
c,d,e,f){c=f.extend(c);a.Oa(c,b);return{controlsDescendantBindings:!0}}};a.h.ea.let=!0;var Q={};a.c.options={init:function(b){if("select"!==a.a.R(b))throw Error("options binding applies only to SELECT elements");for(;0<b.length;)b.remove(0);return{controlsDescendantBindings:!0}},update:function(b,c,d){function e(){return a.a.jb(b.options,function(a){return a.selected})}function f(a,b,c){var d=typeof b;return"function"==d?b(a):"string"==d?a[b]:c}function g(c,d){if(x&&l)a.i.ma(b,a.i.H);else if(t.length){var e=
0<=a.a.A(t,a.w.M(d[0]));a.a.Zc(d[0],e);x&&!e&&a.u.G(a.a.Fb,null,[b,"change"])}}var h=b.multiple,m=0!=b.length&&h?b.scrollTop:null,k=a.a.f(c()),l=d.get("valueAllowUnset")&&d.has("value"),p=d.get("optionsIncludeDestroyed");c={};var q,t=[];l||(h?t=a.a.Mb(e(),a.w.M):0<=b.selectedIndex&&t.push(a.w.M(b.options[b.selectedIndex])));k&&("undefined"==typeof k.length&&(k=[k]),q=a.a.jb(k,function(b){return p||b===n||null===b||!a.a.f(b._destroy)}),d.has("optionsCaption")&&(k=a.a.f(d.get("optionsCaption")),null!==
k&&k!==n&&q.unshift(Q)));var x=!1;c.beforeRemove=function(a){b.removeChild(a)};k=g;d.has("optionsAfterRender")&&"function"==typeof d.get("optionsAfterRender")&&(k=function(b,c){g(0,c);a.u.G(d.get("optionsAfterRender"),null,[c[0],b!==Q?b:n])});a.a.ec(b,q,function(c,e,g){g.length&&(t=!l&&g[0].selected?[a.w.M(g[0])]:[],x=!0);e=b.ownerDocument.createElement("option");c===Q?(a.a.Bb(e,d.get("optionsCaption")),a.w.cb(e,n)):(g=f(c,d.get("optionsValue"),c),a.w.cb(e,a.a.f(g)),c=f(c,d.get("optionsText"),g),
a.a.Bb(e,c));return[e]},c,k);if(!l){var B;h?B=t.length&&e().length<t.length:B=t.length&&0<=b.selectedIndex?a.w.M(b.options[b.selectedIndex])!==t[0]:t.length||0<=b.selectedIndex;B&&a.u.G(a.a.Fb,null,[b,"change"])}(l||a.S.Ya())&&a.i.ma(b,a.i.H);a.a.wd(b);m&&20<Math.abs(m-b.scrollTop)&&(b.scrollTop=m)}};a.c.options.$b=a.a.g.Z();a.c.selectedOptions={init:function(b,c,d){function e(){var e=c(),f=[];a.a.D(b.getElementsByTagName("option"),function(b){b.selected&&f.push(a.w.M(b))});a.m.eb(e,d,"selectedOptions",
f)}function f(){var d=a.a.f(c()),e=b.scrollTop;d&&"number"==typeof d.length&&a.a.D(b.getElementsByTagName("option"),function(b){var c=0<=a.a.A(d,a.w.M(b));b.selected!=c&&a.a.Zc(b,c)});b.scrollTop=e}if("select"!=a.a.R(b))throw Error("selectedOptions binding applies only to SELECT elements");var g;a.i.subscribe(b,a.i.H,function(){g?e():(a.a.B(b,"change",e),g=a.o(f,null,{l:b}))},null,{notifyImmediately:!0})},update:function(){}};a.m.wa.selectedOptions=!0;a.c.style={update:function(b,c){var d=a.a.f(c()||
{});a.a.P(d,function(c,d){d=a.a.f(d);if(null===d||d===n||!1===d)d="";if(v)v(b).css(c,d);else if(/^--/.test(c))b.style.setProperty(c,d);else{c=c.replace(/-(\w)/g,function(a,b){return b.toUpperCase()});var g=b.style[c];b.style[c]=d;d===g||b.style[c]!=g||isNaN(d)||(b.style[c]=d+"px")}})}};a.c.submit={init:function(b,c,d,e,f){if("function"!=typeof c())throw Error("The value for a submit binding must be a function");a.a.B(b,"submit",function(a){var d,e=c();try{d=e.call(f.$data,b)}finally{!0!==d&&(a.preventDefault?
a.preventDefault():a.returnValue=!1)}})}};a.c.text={init:function(){return{controlsDescendantBindings:!0}},update:function(b,c){a.a.Bb(b,c())}};a.h.ea.text=!0;(function(){if(A&&A.navigator){var b=function(a){if(a)return parseFloat(a[1])},c=A.navigator.userAgent,d,e,f,g,h;(d=A.opera&&A.opera.version&&parseInt(A.opera.version()))||(h=b(c.match(/Edge\/([^ ]+)$/)))||b(c.match(/Chrome\/([^ ]+)/))||(e=b(c.match(/Version\/([^ ]+) Safari/)))||(f=b(c.match(/Firefox\/([^ ]+)/)))||(g=a.a.W||b(c.match(/MSIE ([^ ]+)/)))||
(g=b(c.match(/rv:([^ )]+)/)))}if(8<=g&&10>g)var m=a.a.g.Z(),k=a.a.g.Z(),l=function(b){var c=this.activeElement;(c=c&&a.a.g.get(c,k))&&c(b)},p=function(b,c){var d=b.ownerDocument;a.a.g.get(d,m)||(a.a.g.set(d,m,!0),a.a.B(d,"selectionchange",l));a.a.g.set(b,k,c)};a.c.textInput={init:function(b,c,k){function l(c,d){a.a.B(b,c,d)}function m(){var d=a.a.f(c());if(null===d||d===n)d="";L!==n&&d===L?a.a.setTimeout(m,4):b.value!==d&&(y=!0,b.value=d,y=!1,v=b.value)}function r(){w||(L=b.value,w=a.a.setTimeout(z,
4))}function z(){clearTimeout(w);L=w=n;var d=b.value;v!==d&&(v=d,a.m.eb(c(),k,"textInput",d))}var v=b.value,w,L,A=9==a.a.W?r:z,y=!1;g&&l("keypress",z);11>g&&l("propertychange",function(a){y||"value"!==a.propertyName||A(a)});8==g&&(l("keyup",z),l("keydown",z));p&&(p(b,A),l("dragend",r));(!g||9<=g)&&l("input",A);5>e&&"textarea"===a.a.R(b)?(l("keydown",r),l("paste",r),l("cut",r)):11>d?l("keydown",r):4>f?(l("DOMAutoComplete",z),l("dragdrop",z),l("drop",z)):h&&"number"===b.type&&l("keydown",r);l("change",
z);l("blur",z);a.o(m,null,{l:b})}};a.m.wa.textInput=!0;a.c.textinput={preprocess:function(a,b,c){c("textInput",a)}}})();a.c.uniqueName={init:function(b,c){if(c()){var d="ko_unique_"+ ++a.c.uniqueName.rd;a.a.Yc(b,d)}}};a.c.uniqueName.rd=0;a.c.using={init:function(b,c,d,e,f){var g;d.has("as")&&(g={as:d.get("as"),noChildContext:d.get("noChildContext")});c=f.createChildContext(c,g);a.Oa(c,b);return{controlsDescendantBindings:!0}}};a.h.ea.using=!0;a.c.value={init:function(b,c,d){var e=a.a.R(b),f="input"==
e;if(!f||"checkbox"!=b.type&&"radio"!=b.type){var g=[],h=d.get("valueUpdate"),m=!1,k=null;h&&("string"==typeof h?g=[h]:g=a.a.wc(h),a.a.Pa(g,"change"));var l=function(){k=null;m=!1;var e=c(),f=a.w.M(b);a.m.eb(e,d,"value",f)};!a.a.W||!f||"text"!=b.type||"off"==b.autocomplete||b.form&&"off"==b.form.autocomplete||-1!=a.a.A(g,"propertychange")||(a.a.B(b,"propertychange",function(){m=!0}),a.a.B(b,"focus",function(){m=!1}),a.a.B(b,"blur",function(){m&&l()}));a.a.D(g,function(c){var d=l;a.a.Ud(c,"after")&&
(d=function(){k=a.w.M(b);a.a.setTimeout(l,0)},c=c.substring(5));a.a.B(b,c,d)});var p;p=f&&"file"==b.type?function(){var d=a.a.f(c());null===d||d===n||""===d?b.value="":a.u.G(l)}:function(){var f=a.a.f(c()),g=a.w.M(b);if(null!==k&&f===k)a.a.setTimeout(p,0);else if(f!==g||g===n)"select"===e?(g=d.get("valueAllowUnset"),a.w.cb(b,f,g),g||f===a.w.M(b)||a.u.G(l)):a.w.cb(b,f)};if("select"===e){var q;a.i.subscribe(b,a.i.H,function(){q?d.get("valueAllowUnset")?p():l():(a.a.B(b,"change",l),q=a.o(p,null,{l:b}))},
null,{notifyImmediately:!0})}else a.a.B(b,"change",l),a.o(p,null,{l:b})}else a.ib(b,{checkedValue:c})},update:function(){}};a.m.wa.value=!0;a.c.visible={update:function(b,c){var d=a.a.f(c()),e="none"!=b.style.display;d&&!e?b.style.display="":!d&&e&&(b.style.display="none")}};a.c.hidden={update:function(b,c){a.c.visible.update(b,function(){return!a.a.f(c())})}};(function(b){a.c[b]={init:function(c,d,e,f,g){return a.c.event.init.call(this,c,function(){var a={};a[b]=d();return a},e,f,g)}}})("click");
a.ca=function(){};a.ca.prototype.renderTemplateSource=function(){throw Error("Override renderTemplateSource");};a.ca.prototype.createJavaScriptEvaluatorBlock=function(){throw Error("Override createJavaScriptEvaluatorBlock");};a.ca.prototype.makeTemplateSource=function(b,c){if("string"==typeof b){c=c||w;var d=c.getElementById(b);if(!d)throw Error("Cannot find template with ID "+b);return new a.C.F(d)}if(1==b.nodeType||8==b.nodeType)return new a.C.ia(b);throw Error("Unknown template type: "+b);};a.ca.prototype.renderTemplate=
function(a,c,d,e){a=this.makeTemplateSource(a,e);return this.renderTemplateSource(a,c,d,e)};a.ca.prototype.isTemplateRewritten=function(a,c){return!1===this.allowTemplateRewriting?!0:this.makeTemplateSource(a,c).data("isRewritten")};a.ca.prototype.rewriteTemplate=function(a,c,d){a=this.makeTemplateSource(a,d);c=c(a.text());a.text(c);a.data("isRewritten",!0)};a.b("templateEngine",a.ca);a.kc=function(){function b(b,c,d,h){b=a.m.ac(b);for(var m=a.m.Ra,k=0;k<b.length;k++){var l=b[k].key;if(Object.prototype.hasOwnProperty.call(m,
l)){var p=m[l];if("function"===typeof p){if(l=p(b[k].value))throw Error(l);}else if(!p)throw Error("This template engine does not support the '"+l+"' binding within its templates");}}d="ko.__tr_ambtns(function($context,$element){return(function(){return{ "+a.m.vb(b,{valueAccessors:!0})+" } })()},'"+d.toLowerCase()+"')";return h.createJavaScriptEvaluatorBlock(d)+c}var c=/(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'|[^>]*))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi,
d=/\x3c!--\s*ko\b\s*([\s\S]*?)\s*--\x3e/g;return{xd:function(b,c,d){c.isTemplateRewritten(b,d)||c.rewriteTemplate(b,function(b){return a.kc.Ld(b,c)},d)},Ld:function(a,f){return a.replace(c,function(a,c,d,e,l){return b(l,c,d,f)}).replace(d,function(a,c){return b(c,"\x3c!-- ko --\x3e","#comment",f)})},md:function(b,c){return a.aa.Xb(function(d,h){var m=d.nextSibling;m&&m.nodeName.toLowerCase()===c&&a.ib(m,b,h)})}}}();a.b("__tr_ambtns",a.kc.md);(function(){a.C={};a.C.F=function(b){if(this.F=b){var c=
a.a.R(b);this.ab="script"===c?1:"textarea"===c?2:"template"==c&&b.content&&11===b.content.nodeType?3:4}};a.C.F.prototype.text=function(){var b=1===this.ab?"text":2===this.ab?"value":"innerHTML";if(0==arguments.length)return this.F[b];var c=arguments[0];"innerHTML"===b?a.a.fc(this.F,c):this.F[b]=c};var b=a.a.g.Z()+"_";a.C.F.prototype.data=function(c){if(1===arguments.length)return a.a.g.get(this.F,b+c);a.a.g.set(this.F,b+c,arguments[1])};var c=a.a.g.Z();a.C.F.prototype.nodes=function(){var b=this.F;
if(0==arguments.length){var e=a.a.g.get(b,c)||{},f=e.lb||(3===this.ab?b.content:4===this.ab?b:n);if(!f||e.jd){var g=this.text();g&&g!==e.bb&&(f=a.a.Md(g,b.ownerDocument),a.a.g.set(b,c,{lb:f,bb:g,jd:!0}))}return f}e=arguments[0];this.ab!==n&&this.text("");a.a.g.set(b,c,{lb:e})};a.C.ia=function(a){this.F=a};a.C.ia.prototype=new a.C.F;a.C.ia.prototype.constructor=a.C.ia;a.C.ia.prototype.text=function(){if(0==arguments.length){var b=a.a.g.get(this.F,c)||{};b.bb===n&&b.lb&&(b.bb=b.lb.innerHTML);return b.bb}a.a.g.set(this.F,
c,{bb:arguments[0]})};a.b("templateSources",a.C);a.b("templateSources.domElement",a.C.F);a.b("templateSources.anonymousTemplate",a.C.ia)})();(function(){function b(b,c,d){var e;for(c=a.h.nextSibling(c);b&&(e=b)!==c;)b=a.h.nextSibling(e),d(e,b)}function c(c,d){if(c.length){var e=c[0],f=c[c.length-1],g=e.parentNode,h=a.ga.instance,m=h.preprocessNode;if(m){b(e,f,function(a,b){var c=a.previousSibling,d=m.call(h,a);d&&(a===e&&(e=d[0]||b),a===f&&(f=d[d.length-1]||c))});c.length=0;if(!e)return;e===f?c.push(e):
(c.push(e,f),a.a.Ua(c,g))}b(e,f,function(b){1!==b.nodeType&&8!==b.nodeType||a.vc(d,b)});b(e,f,function(b){1!==b.nodeType&&8!==b.nodeType||a.aa.cd(b,[d])});a.a.Ua(c,g)}}function d(a){return a.nodeType?a:0<a.length?a[0]:null}function e(b,e,f,h,m){m=m||{};var n=(b&&d(b)||f||{}).ownerDocument,B=m.templateEngine||g;a.kc.xd(f,B,n);f=B.renderTemplate(f,h,m,n);if("number"!=typeof f.length||0<f.length&&"number"!=typeof f[0].nodeType)throw Error("Template engine must return an array of DOM nodes");n=!1;switch(e){case "replaceChildren":a.h.va(b,
f);n=!0;break;case "replaceNode":a.a.Xc(b,f);n=!0;break;case "ignoreTargetNode":break;default:throw Error("Unknown renderMode: "+e);}n&&(c(f,h),m.afterRender&&a.u.G(m.afterRender,null,[f,h[m.as||"$data"]]),"replaceChildren"==e&&a.i.ma(b,a.i.H));return f}function f(b,c,d){return a.O(b)?b():"function"===typeof b?b(c,d):b}var g;a.gc=function(b){if(b!=n&&!(b instanceof a.ca))throw Error("templateEngine must inherit from ko.templateEngine");g=b};a.dc=function(b,c,h,m,t){h=h||{};if((h.templateEngine||g)==
n)throw Error("Set a template engine before calling renderTemplate");t=t||"replaceChildren";if(m){var x=d(m);return a.$(function(){var g=c&&c instanceof a.fa?c:new a.fa(c,null,null,null,{exportDependencies:!0}),n=f(b,g.$data,g),g=e(m,t,n,g,h);"replaceNode"==t&&(m=g,x=d(m))},null,{Sa:function(){return!x||!a.a.Sb(x)},l:x&&"replaceNode"==t?x.parentNode:x})}return a.aa.Xb(function(d){a.dc(b,c,h,d,"replaceNode")})};a.Qd=function(b,d,g,h,m){function x(b,c){a.u.G(a.a.ec,null,[h,b,u,g,r,c]);a.i.ma(h,a.i.H)}
function r(a,b){c(b,v);g.afterRender&&g.afterRender(b,a);v=null}function u(a,c){v=m.createChildContext(a,{as:z,noChildContext:g.noChildContext,extend:function(a){a.$index=c;z&&(a[z+"Index"]=c)}});var d=f(b,a,v);return e(h,"ignoreTargetNode",d,v,g)}var v,z=g.as,w=!1===g.includeDestroyed||a.options.foreachHidesDestroyed&&!g.includeDestroyed;if(w||g.beforeRemove||!a.Pc(d))return a.$(function(){var b=a.a.f(d)||[];"undefined"==typeof b.length&&(b=[b]);w&&(b=a.a.jb(b,function(b){return b===n||null===b||
!a.a.f(b._destroy)}));x(b)},null,{l:h});x(d.v());var A=d.subscribe(function(a){x(d(),a)},null,"arrayChange");A.l(h);return A};var h=a.a.g.Z(),m=a.a.g.Z();a.c.template={init:function(b,c){var d=a.a.f(c());if("string"==typeof d||"name"in d)a.h.Ea(b);else if("nodes"in d){d=d.nodes||[];if(a.O(d))throw Error('The "nodes" option must be a plain, non-observable array.');var e=d[0]&&d[0].parentNode;e&&a.a.g.get(e,m)||(e=a.a.Yb(d),a.a.g.set(e,m,!0));(new a.C.ia(b)).nodes(e)}else if(d=a.h.childNodes(b),0<d.length)e=
a.a.Yb(d),(new a.C.ia(b)).nodes(e);else throw Error("Anonymous template defined, but no template content was provided");return{controlsDescendantBindings:!0}},update:function(b,c,d,e,f){var g=c();c=a.a.f(g);d=!0;e=null;"string"==typeof c?c={}:(g="name"in c?c.name:b,"if"in c&&(d=a.a.f(c["if"])),d&&"ifnot"in c&&(d=!a.a.f(c.ifnot)),d&&!g&&(d=!1));"foreach"in c?e=a.Qd(g,d&&c.foreach||[],c,b,f):d?(d=f,"data"in c&&(d=f.createChildContext(c.data,{as:c.as,noChildContext:c.noChildContext,exportDependencies:!0})),
e=a.dc(g,d,c,b)):a.h.Ea(b);f=e;(c=a.a.g.get(b,h))&&"function"==typeof c.s&&c.s();a.a.g.set(b,h,!f||f.ja&&!f.ja()?n:f)}};a.m.Ra.template=function(b){b=a.m.ac(b);return 1==b.length&&b[0].unknown||a.m.Id(b,"name")?null:"This template engine does not support anonymous templates nested within its templates"};a.h.ea.template=!0})();a.b("setTemplateEngine",a.gc);a.b("renderTemplate",a.dc);a.a.Kc=function(a,c,d){if(a.length&&c.length){var e,f,g,h,m;for(e=f=0;(!d||e<d)&&(h=a[f]);++f){for(g=0;m=c[g];++g)if(h.value===
m.value){h.moved=m.index;m.moved=h.index;c.splice(g,1);e=g=0;break}e+=g}}};a.a.Pb=function(){function b(b,d,e,f,g){var h=Math.min,m=Math.max,k=[],l,p=b.length,q,n=d.length,r=n-p||1,v=p+n+1,u,w,z;for(l=0;l<=p;l++)for(w=u,k.push(u=[]),z=h(n,l+r),q=m(0,l-1);q<=z;q++)u[q]=q?l?b[l-1]===d[q-1]?w[q-1]:h(w[q]||v,u[q-1]||v)+1:q+1:l+1;h=[];m=[];r=[];l=p;for(q=n;l||q;)n=k[l][q]-1,q&&n===k[l][q-1]?m.push(h[h.length]={status:e,value:d[--q],index:q}):l&&n===k[l-1][q]?r.push(h[h.length]={status:f,value:b[--l],index:l}):
(--q,--l,g.sparse||h.push({status:"retained",value:d[q]}));a.a.Kc(r,m,!g.dontLimitMoves&&10*p);return h.reverse()}return function(a,d,e){e="boolean"===typeof e?{dontLimitMoves:e}:e||{};a=a||[];d=d||[];return a.length<d.length?b(a,d,"added","deleted",e):b(d,a,"deleted","added",e)}}();a.b("utils.compareArrays",a.a.Pb);(function(){function b(b,c,d,h,m){var k=[],l=a.$(function(){var l=c(d,m,a.a.Ua(k,b))||[];0<k.length&&(a.a.Xc(k,l),h&&a.u.G(h,null,[d,l,m]));k.length=0;a.a.Nb(k,l)},null,{l:b,Sa:function(){return!a.a.kd(k)}});
return{Y:k,$:l.ja()?l:n}}var c=a.a.g.Z(),d=a.a.g.Z();a.a.ec=function(e,f,g,h,m,k){function l(b){y={Aa:b,pb:a.ta(w++)};v.push(y);r||F.push(y)}function p(b){y=t[b];w!==y.pb.v()&&D.push(y);y.pb(w++);a.a.Ua(y.Y,e);v.push(y)}function q(b,c){if(b)for(var d=0,e=c.length;d<e;d++)a.a.D(c[d].Y,function(a){b(a,d,c[d].Aa)})}f=f||[];"undefined"==typeof f.length&&(f=[f]);h=h||{};var t=a.a.g.get(e,c),r=!t,v=[],u=0,w=0,z=[],A=[],C=[],D=[],F=[],y,I=0;if(r)a.a.D(f,l);else{if(!k||t&&t._countWaitingForRemove){var E=
a.a.Mb(t,function(a){return a.Aa});k=a.a.Pb(E,f,{dontLimitMoves:h.dontLimitMoves,sparse:!0})}for(var E=0,G,H,K;G=k[E];E++)switch(H=G.moved,K=G.index,G.status){case "deleted":for(;u<K;)p(u++);H===n&&(y=t[u],y.$&&(y.$.s(),y.$=n),a.a.Ua(y.Y,e).length&&(h.beforeRemove&&(v.push(y),I++,y.Aa===d?y=null:C.push(y)),y&&z.push.apply(z,y.Y)));u++;break;case "added":for(;w<K;)p(u++);H!==n?(A.push(v.length),p(H)):l(G.value)}for(;w<f.length;)p(u++);v._countWaitingForRemove=I}a.a.g.set(e,c,v);q(h.beforeMove,D);a.a.D(z,
h.beforeRemove?a.oa:a.removeNode);var M,O,P;try{P=e.ownerDocument.activeElement}catch(N){}if(A.length)for(;(E=A.shift())!=n;){y=v[E];for(M=n;E;)if((O=v[--E].Y)&&O.length){M=O[O.length-1];break}for(f=0;u=y.Y[f];M=u,f++)a.h.Wb(e,u,M)}for(E=0;y=v[E];E++){y.Y||a.a.extend(y,b(e,g,y.Aa,m,y.pb));for(f=0;u=y.Y[f];M=u,f++)a.h.Wb(e,u,M);!y.Ed&&m&&(m(y.Aa,y.Y,y.pb),y.Ed=!0,M=y.Y[y.Y.length-1])}P&&e.ownerDocument.activeElement!=P&&P.focus();q(h.beforeRemove,C);for(E=0;E<C.length;++E)C[E].Aa=d;q(h.afterMove,D);
q(h.afterAdd,F)}})();a.b("utils.setDomNodeChildrenFromArrayMapping",a.a.ec);a.ba=function(){this.allowTemplateRewriting=!1};a.ba.prototype=new a.ca;a.ba.prototype.constructor=a.ba;a.ba.prototype.renderTemplateSource=function(b,c,d,e){if(c=(9>a.a.W?0:b.nodes)?b.nodes():null)return a.a.la(c.cloneNode(!0).childNodes);b=b.text();return a.a.ua(b,e)};a.ba.Ma=new a.ba;a.gc(a.ba.Ma);a.b("nativeTemplateEngine",a.ba);(function(){a.$a=function(){var a=this.Hd=function(){if(!v||!v.tmpl)return 0;try{if(0<=v.tmpl.tag.tmpl.open.toString().indexOf("__"))return 2}catch(a){}return 1}();
this.renderTemplateSource=function(b,e,f,g){g=g||w;f=f||{};if(2>a)throw Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");var h=b.data("precompiled");h||(h=b.text()||"",h=v.template(null,"{{ko_with $item.koBindingContext}}"+h+"{{/ko_with}}"),b.data("precompiled",h));b=[e.$data];e=v.extend({koBindingContext:e},f.templateOptions);e=v.tmpl(h,b,e);e.appendTo(g.createElement("div"));v.fragments={};return e};this.createJavaScriptEvaluatorBlock=function(a){return"{{ko_code ((function() { return "+
a+" })()) }}"};this.addTemplate=function(a,b){w.write("<script type='text/html' id='"+a+"'>"+b+"\x3c/script>")};0<a&&(v.tmpl.tag.ko_code={open:"__.push($1 || '');"},v.tmpl.tag.ko_with={open:"with($1) {",close:"} "})};a.$a.prototype=new a.ca;a.$a.prototype.constructor=a.$a;var b=new a.$a;0<b.Hd&&a.gc(b);a.b("jqueryTmplTemplateEngine",a.$a)})()})})();})();

/*! WeakMap shim
 * (The MIT License)
 *
 * Copyright (c) 2012 Brandon Benvie <http://bbenvie.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
 * associated documentation files (the 'Software'), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included with all copies or
 * substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
// Original WeakMap implementation by Gozala @ https://gist.github.com/1269991
// Updated and bugfixed by Raynos @ https://gist.github.com/1638059
// Expanded by Benvie @ https://github.com/Benvie/harmony-collections
// This is the version used by knockout-es5. Modified by Steve Sanderson as follows:
// [1] Deleted weakmap.min.js (it's not useful as it would be out of sync with weakmap.js now I'm editing it)
// [2] Since UglifyJS strips inline function names (and you can't disable that without disabling name mangling
//     entirely), insert code that re-adds function names
void function(a,b,c){function d(a,b,c){return"function"==typeof b&&(c=b,b=e(c).replace(/_$/,"")),j(a,b,{configurable:!0,writable:!0,value:c})}function e(a){return"function"!=typeof a?"":"_name"in a?a._name:"name"in a?a.name:k.call(a).match(n)[1]}function f(a,b){
// Undo the name-stripping that UglifyJS does
return b._name=a,b}function g(a){function b(b,e){return e||2===arguments.length?d.set(b,e):(e=d.get(b),e===c&&(e=a(b),d.set(b,e))),e}var d=new p;return a||(a=q),b}var h=Object.getOwnPropertyNames,i="object"==typeof window?Object.getOwnPropertyNames(window):[],j=Object.defineProperty,k=Function.prototype.toString,l=Object.create,m=Object.prototype.hasOwnProperty,n=/^\n?function\s?(\w*)?_?\(/,o=function(){function a(){var a=g(),c={};this.unlock=function(d){var e=n(d);if(m.call(e,a))return e[a](c);var f=l(null,b);return j(e,a,{value:function(a){if(a===c)return f}}),f}}var b={value:{writable:!0,value:c}},e=l(null),g=function(){var a=Math.random().toString(36).slice(2);return a in e?g():e[a]=a},k=g(),n=function(a){if(m.call(a,k))return a[k];if(!Object.isExtensible(a))throw new TypeError("Object must be extensible");var b=l(null);return j(a,k,{value:b}),b};
// common per-object storage area made visible by patching getOwnPropertyNames'
return d(Object,f("getOwnPropertyNames",function(a){
// gh-43
var b,c=Object(a);
// Fixes for debuggers:
// 1) Some objects lack .toString(), calling it on them make Chrome
// debugger fail when inspecting variables.
// 2) Window.prototype methods and properties are private in IE11 and
// throw 'Invalid calling object'.
if(c!==Window.prototype&&"toString"in c&&"[object Window]"===c.toString())try{b=h(a)}catch(a){b=i}else b=h(a);return m.call(a,k)&&b.splice(b.indexOf(k),1),b})),d(a.prototype,f("get",function(a){return this.unlock(a).value})),d(a.prototype,f("set",function(a,b){this.unlock(a).value=b})),a}(),p=function(g){function h(b){return this===a||null==this||this===h.prototype?new h(b):(p(this,new o),void r(this,b))}function i(a){n(a);var d=q(this).get(a);return d===b?c:d}function j(a,d){n(a),
// store a token for explicit undefined so that "has" works correctly
q(this).set(a,d===c?b:d)}function k(a){return n(a),q(this).get(a)!==c}function l(a){n(a);var b=q(this),d=b.get(a)!==c;return b.set(a,c),d}function m(){return q(this),"[object WeakMap]"}var n=function(a){if(null==a||"object"!=typeof a&&"function"!=typeof a)throw new TypeError("Invalid WeakMap key")},p=function(a,b){var c=g.unlock(a);if(c.value)throw new TypeError("Object is already a WeakMap");c.value=b},q=function(a){var b=g.unlock(a).value;if(!b)throw new TypeError("WeakMap is not generic");return b},r=function(a,b){null!==b&&"object"==typeof b&&"function"==typeof b.forEach&&b.forEach(function(c,d){c instanceof Array&&2===c.length&&j.call(a,b[d][0],b[d][1])})};
// Undo the function-name stripping that UglifyJS does
i._name="get",j._name="set",k._name="has",m._name="toString";var s=(""+Object).split("Object"),t=f("toString",function(){return s[0]+e(this)+s[1]});d(t,t);var u={__proto__:[]}instanceof Array?function(a){a.__proto__=t}:function(a){d(a,t)};return u(h),[m,i,j,k,l].forEach(function(a){d(h.prototype,a),u(a)}),h}(new o),q=Object.create?function(){return Object.create(null)}:function(){return{}};"undefined"!=typeof module?module.exports=p:"undefined"!=typeof exports?exports.WeakMap=p:"WeakMap"in a||(a.WeakMap=p),p.createStorage=g,a.WeakMap&&(a.WeakMap.createStorage=g)}(function(){return this}()),/*!
 * Knockout ES5 plugin - https://github.com/SteveSanderson/knockout-es5
 * Copyright (c) Steve Sanderson
 * MIT license
 */
function(a,b){"use strict";
// Model tracking
// --------------
//
// This is the central feature of Knockout-ES5. We augment model objects by converting properties
// into ES5 getter/setter pairs that read/write an underlying Knockout observable. This means you can
// use plain JavaScript syntax to read/write the property while still getting the full benefits of
// Knockout's automatic dependency detection and notification triggering.
//
// For comparison, here's Knockout ES3-compatible syntax:
//
//     var firstNameLength = myModel.user().firstName().length; // Read
//     myModel.user().firstName('Bert'); // Write
//
// ... versus Knockout-ES5 syntax:
//
//     var firstNameLength = myModel.user.firstName.length; // Read
//     myModel.user.firstName = 'Bert'; // Write
// `ko.track(model)` converts each property on the given model object into a getter/setter pair that
// wraps a Knockout observable. Optionally specify an array of property names to wrap; otherwise we
// wrap all properties. If any of the properties are already observables, we replace them with
// ES5 getter/setter pairs that wrap your original observable instances. In the case of readonly
// ko.computed properties, we simply do not define a setter (so attempted writes will be ignored,
// which is how ES5 readonly properties normally behave).
//
// By design, this does *not* recursively walk child object properties, because making literally
// everything everywhere independently observable is usually unhelpful. When you do want to track
// child object properties independently, define your own class for those child objects and put
// a separate ko.track call into its constructor --- this gives you far more control.
/**
   * @param {object} obj
   * @param {object|array.<string>} propertyNamesOrSettings
   * @param {boolean} propertyNamesOrSettings.deep Use deep track.
   * @param {array.<string>} propertyNamesOrSettings.fields Array of property names to wrap.
   * todo: @param {array.<string>} propertyNamesOrSettings.exclude Array of exclude property names to wrap.
   * todo: @param {function(string, *):boolean} propertyNamesOrSettings.filter Function to filter property 
   *   names to wrap. A function that takes ... params
   * @return {object}
   */
function c(a,b){if(!a||"object"!=typeof a)throw new Error("When calling ko.track, you must pass an object as the first parameter.");var c;
// defaults
return i(b)?(b.deep=b.deep||!1,b.fields=b.fields||Object.getOwnPropertyNames(a),b.lazy=b.lazy||!1,h(a,b.fields,b)):(c=b||Object.getOwnPropertyNames(a),h(a,c,{})),a}function d(a){return a.name?a.name:(a.toString().trim().match(A)||[])[1]}function e(a){return a&&"object"==typeof a&&"Object"===d(a.constructor)}function f(a,c,d){var e=w.isObservable(a),f=!e&&Array.isArray(a),g=e?a:f?w.observableArray(a):w.observable(a);
// add check in case the object is already an observable array
return d[c]=function(){return g},(f||e&&"push"in g)&&m(w,g),{configurable:!0,enumerable:!0,get:g,set:w.isWriteableObservable(g)?g:b}}function g(a,b,c){function d(a,b){return e?b?e(a):e:Array.isArray(a)?(e=w.observableArray(a),m(w,e),e):e=w.observable(a)}if(w.isObservable(a))
// no need to be lazy if we already have an observable
return f(a,b,c);var e;return c[b]=function(){return d(a)},{configurable:!0,enumerable:!0,get:function(){return d(a)()},set:function(a){d(a,!0)}}}function h(a,b,c){if(b.length){var d=j(a,!0),i={};b.forEach(function(b){
// Skip properties that are already tracked
if(!(b in d)&&Object.getOwnPropertyDescriptor(a,b).configurable!==!1)
// Skip properties where descriptor can't be redefined
{var j=a[b];i[b]=(c.lazy?g:f)(j,b,d),c.deep&&e(j)&&h(j,Object.keys(j),c)}}),Object.defineProperties(a,i)}}function i(a){return!!a&&"object"==typeof a&&a.constructor===Object}
// Gets or creates the hidden internal key-value collection of observables corresponding to
// properties on the model object.
function j(a,b){y||(y=x());var c=y.get(a);return!c&&b&&(c={},y.set(a,c)),c}
// Removes the internal references to observables mapped to the specified properties
// or the entire object reference if no properties are passed in. This allows the
// observables to be replaced and tracked again.
function k(a,b){if(y)if(1===arguments.length)y.delete(a);else{var c=j(a,!1);c&&b.forEach(function(a){delete c[a]})}}
// Computed properties
// -------------------
//
// The preceding code is already sufficient to upgrade ko.computed model properties to ES5
// getter/setter pairs (or in the case of readonly ko.computed properties, just a getter).
// These then behave like a regular property with a getter function, except they are smarter:
// your evaluator is only invoked when one of its dependencies changes. The result is cached
// and used for all evaluations until the next time a dependency changes).
//
// However, instead of forcing developers to declare a ko.computed property explicitly, it's
// nice to offer a utility function that declares a computed getter directly.
// Implements `ko.defineProperty`
function l(a,b,d){var e=this,f={owner:a,deferEvaluation:!0};if("function"==typeof d)f.read=d;else{if("value"in d)throw new Error('For ko.defineProperty, you must not specify a "value" for the property. You must provide a "get" function.');if("function"!=typeof d.get)throw new Error('For ko.defineProperty, the third parameter must be either an evaluator function, or an options object containing a function called "get".');f.read=d.get,f.write=d.set}return a[b]=e.computed(f),c.call(e,a,[b]),a}
// Array handling
// --------------
//
// Arrays are special, because unlike other property types, they have standard mutator functions
// (`push`/`pop`/`splice`/etc.) and it's desirable to trigger a change notification whenever one of
// those mutator functions is invoked.
//
// Traditionally, Knockout handles this by putting special versions of `push`/`pop`/etc. on observable
// arrays that mutate the underlying array and then trigger a notification. That approach doesn't
// work for Knockout-ES5 because properties now return the underlying arrays, so the mutator runs
// in the context of the underlying array, not any particular observable:
//
//     // Operates on the underlying array value
//     myModel.someCollection.push('New value');
//
// To solve this, Knockout-ES5 detects array values, and modifies them as follows:
//  1. Associates a hidden subscribable with each array instance that it encounters
//  2. Intercepts standard mutators (`push`/`pop`/etc.) and makes them trigger the subscribable
// Then, for model properties whose values are arrays, the property's underlying observable
// subscribes to the array subscribable, so it can trigger a change notification after mutation.
// Given an observable that underlies a model property, watch for any array value that might
// be assigned as the property value, and hook into its change events
function m(a,b){var c=null;a.computed(function(){
// Unsubscribe to any earlier array instance
c&&(c.dispose(),c=null);
// Subscribe to the new array instance
var d=b();d instanceof Array&&(c=n(a,b,d))})}
// Listens for array mutations, and when they happen, cause the observable to fire notifications.
// This is used to make model properties of type array fire notifications when the array changes.
// Returns a subscribable that can later be disposed.
function n(a,b,c){var d=o(a,c);return d.subscribe(b)}
// Gets or creates a subscribable that fires after each array mutation
function o(a,b){z||(z=x());var c=z.get(b);if(!c){c=new a.subscribable,z.set(b,c);var d={};p(b,c,d),q(a,b,c,d)}return c}
// After each array mutation, fires a notification on the given subscribable
function p(a,b,c){["pop","push","reverse","shift","sort","splice","unshift"].forEach(function(d){var e=a[d];a[d]=function(){var a=e.apply(this,arguments);return c.pause!==!0&&b.notifySubscribers(this),a}})}
// Adds Knockout's additional array mutation functions to the array
function q(a,b,c,d){["remove","removeAll","destroy","destroyAll","replace"].forEach(function(e){
// Make it a non-enumerable property for consistency with standard Array functions
Object.defineProperty(b,e,{enumerable:!1,value:function(){var f;
// These additional array mutators are built using the underlying push/pop/etc.
// mutators, which are wrapped to trigger notifications. But we don't want to
// trigger multiple notifications, so pause the push/pop/etc. wrappers and
// delivery only one notification at the end of the process.
d.pause=!0;try{
// Creates a temporary observableArray that can perform the operation.
f=a.observableArray.fn[e].apply(a.observableArray(b),arguments)}finally{d.pause=!1}return c.notifySubscribers(b),f}})})}
// Static utility functions
// ------------------------
//
// Since Knockout-ES5 sets up properties that return values, not observables, you can't
// trivially subscribe to the underlying observables (e.g., `someProperty.subscribe(...)`),
// or tell them that object values have mutated, etc. To handle this, we set up some
// extra utility functions that can return or work with the underlying observables.
// Returns the underlying observable associated with a model property (or `null` if the
// model or property doesn't exist, or isn't associated with an observable). This means
// you can subscribe to the property, e.g.:
//
//     ko.getObservable(model, 'propertyName')
//       .subscribe(function(newValue) { ... });
function r(a,b){if(!a||"object"!=typeof a)return null;var c=j(a,!1);if(c&&b in c)return c[b]();var d=a[b];return w.isObservable(d)?d:null}
// Returns a boolean indicating whether the property on the object has an underlying
// observables. This does the check in a way not to create an observable if the
// object was created with lazily created observables
function s(a,b){if(!a||"object"!=typeof a)return!1;var c=j(a,!1);return!!c&&b in c}
// Causes a property's associated observable to fire a change notification. Useful when
// the property value is a complex object and you've modified a child property.
function t(a,b){var c=r(a,b);c&&c.valueHasMutated()}
// Module initialisation
// ---------------------
//
// When this script is first evaluated, it works out what kind of module loading scenario
// it is in (Node.js or a browser `<script>` tag), stashes a reference to its dependencies
// (currently that's just the WeakMap shim), and then finally attaches itself to whichever
// instance of Knockout.js it can find.
// Extends a Knockout instance with Knockout-ES5 functionality
function u(a){a.track=c,a.untrack=k,a.getObservable=r,a.valueHasMutated=t,a.defineProperty=l,
// todo: test it, maybe added it to ko. directly
a.es5={getAllObservablesForObject:j,notifyWhenPresentOrFutureArrayValuesMutate:m,isTracked:s}}
// Determines which module loading scenario we're in, grabs dependencies, and attaches to KO
function v(){if("object"==typeof exports&&"object"==typeof module){
// Node.js case - load KO and WeakMap modules synchronously
w=require("knockout");var b=a.WeakMap||require("../lib/weakmap");u(w),x=function(){return new b},module.exports=w}else"function"==typeof define&&define.amd?define('KnockoutES5',["knockout"],function(b){return w=b,u(b),x=function(){return new a.WeakMap},b}):"ko"in a&&(
// Non-module case - attach to the global instance, and assume a global WeakMap constructor
w=a.ko,u(a.ko),x=function(){return new a.WeakMap})}var w,x,y,z,A=/^function\s*([^\s(]+)/;v()}("undefined"!=typeof window?window:"undefined"!=typeof global?global:this);
/*! markdown-it-sanitizer 0.4.3 https://github.com/svbergerem/markdown-it-sanitizer @license MIT */
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define('markdown-it-sanitizer',[],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.markdownitSanitizer=e()}}(function(){return function e(t,n,r){function o(l,f){if(!n[l]){if(!t[l]){var a="function"==typeof require&&require;if(!f&&a)return a(l,!0);if(i)return i(l,!0);var s=new Error("Cannot find module '"+l+"'");throw s.code="MODULE_NOT_FOUND",s}var c=n[l]={exports:{}};t[l][0].call(c.exports,function(e){var n=t[l][1][e];return o(n?n:e)},c,c.exports,e,t,n,r)}return n[l].exports}for(var i="function"==typeof require&&require,l=0;l<r.length;l++)o(r[l]);return o}({1:[function(e,t,n){"use strict";t.exports=function(e,t){function n(e){var t=l.match(e);return t&&1===t.length&&0===t[0].index&&t[0].lastIndex===e.length?t[0].url:null}function r(e){return e=e.replace(/<[^<>]*>?/gi,function(e){var t,r,o,i,l,a;return/(^<->|^<-\s|^<3\s)/.test(e)?e:(t=e.match(u),t&&(r=t[1],o=n(r.match(/src="([^"<>]*)"/i)[1]),i=r.match(/alt="([^"<>]*)"/i),i=i&&"undefined"!=typeof i[1]?i[1]:"",l=r.match(/title="([^"<>]*)"/i),l=l&&"undefined"!=typeof l[1]?l[1]:"",o&&p.test(o))?""!==y?'<img src="'+o+'" alt="'+i+'" title="'+l+'" class="'+y+'">':'<img src="'+o+'" alt="'+i+'" title="'+l+'">':(a=v.indexOf("a"),t=e.match(s),t&&(r=t[1],o=n(r.match(/href="([^"<>]*)"/i)[1]),l=r.match(/title="([^"<>]*)"/i),l=l&&"undefined"!=typeof l[1]?l[1]:"",o&&h.test(o))?(k=!0,b[a]+=1,'<a href="'+o+'" title="'+l+'" target="_blank">'):(t=/<\/a>/i.test(e))?(k=!0,b[a]-=1,b[a]<0&&(x[a]=!0),"</a>"):(t=e.match(/<(br|hr)\s?\/?>/i))?"<"+t[1].toLowerCase()+">":(t=e.match(/<(\/?)(b|blockquote|code|em|h[1-6]|li|ol(?: start="\d+")?|p|pre|s|sub|sup|strong|ul)>/i),t&&!/<\/ol start="\d+"/i.test(e)?(k=!0,a=v.indexOf(t[2].toLowerCase().split(" ")[0]),"/"===t[1]?b[a]-=1:b[a]+=1,b[a]<0&&(x[a]=!0),"<"+t[1]+t[2].toLowerCase()+">"):g===!0?"":f(e))))})}function o(e){var t,n,o;for(d=0;d<v.length;d++)b[d]=0;for(d=0;d<v.length;d++)x[d]=!1;for(k=!1,n=0;n<e.tokens.length;n++)if("html_block"===e.tokens[n].type&&(e.tokens[n].content=r(e.tokens[n].content)),"inline"===e.tokens[n].type)for(o=e.tokens[n].children,t=0;t<o.length;t++)"html_inline"===o[t].type&&(o[t].content=r(o[t].content))}function i(e){function t(e,t){var n,r;return n="a"===t?RegExp('<a href="[^"<>]*" title="[^"<>]*" target="_blank">',"g"):"ol"===t?/<ol(?: start="\d+")?>/g:RegExp("<"+t+">","g"),r=RegExp("</"+t+">","g"),m===!0?(e=e.replace(n,""),e=e.replace(r,"")):(e=e.replace(n,function(e){return f(e)}),e=e.replace(r,function(e){return f(e)})),e}function n(e){var n;for(n=0;n<v.length;n++)x[n]===!0&&(e=t(e,v[n]));return e}if(k!==!1){var r,o;for(d=0;d<v.length;d++)0!==b[d]&&(x[d]=!0);for(r=0;r<e.tokens.length;r++)if("html_block"!==e.tokens[r].type){if("inline"===e.tokens[r].type)for(o=e.tokens[r].children,d=0;d<o.length;d++)"html_inline"===o[d].type&&(o[d].content=n(o[d].content))}else e.tokens[r].content=n(e.tokens[r].content)}}var l=e.linkify,f=e.utils.escapeHtml,a='<a\\s([^<>]*href="[^"<>]*"[^<>]*)\\s?>',s=RegExp(a,"i"),c='<img\\s([^<>]*src="[^"<>]*"[^<>]*)\\s?\\/?>',u=RegExp(c,"i"),p=/^(?:https?:)?\/\//i,h=/^(?:https?:\/\/|ftp:\/\/|\/\/|mailto:|xmpp:)/i;t=t?t:{};var d,g="undefined"!=typeof t.removeUnknown&&t.removeUnknown,m="undefined"!=typeof t.removeUnbalanced&&t.removeUnbalanced,y="undefined"!=typeof t.imageClass?t.imageClass:"",k=!1,v=["a","b","blockquote","code","em","h1","h2","h3","h4","h5","h6","li","ol","p","pre","s","sub","sup","strong","ul"],b=new Array(v.length),x=new Array(v.length);for(d=0;d<v.length;d++)b[d]=0;for(d=0;d<v.length;d++)x[d]=!1;e.core.ruler.after("linkify","sanitize_inline",o),e.core.ruler.after("sanitize_inline","sanitize_balance",i)}},{}]},{},[1])(1)});

/*! markdown-it 7.0.1 https://github.com//markdown-it/markdown-it @license MIT */
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define('markdown-it',[],e);else{var r;r="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,r.markdownit=e()}}(function(){var e;return function e(r,t,n){function s(i,a){if(!t[i]){if(!r[i]){var c="function"==typeof require&&require;if(!a&&c)return c(i,!0);if(o)return o(i,!0);var l=new Error("Cannot find module '"+i+"'");throw l.code="MODULE_NOT_FOUND",l}var u=t[i]={exports:{}};r[i][0].call(u.exports,function(e){var t=r[i][1][e];return s(t?t:e)},u,u.exports,e,r,t,n)}return t[i].exports}for(var o="function"==typeof require&&require,i=0;i<n.length;i++)s(n[i]);return s}({1:[function(e,r,t){"use strict";r.exports=e("entities/maps/entities.json")},{"entities/maps/entities.json":52}],2:[function(e,r,t){"use strict";r.exports=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","meta","nav","noframes","ol","optgroup","option","p","param","pre","section","source","title","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"]},{}],3:[function(e,r,t){"use strict";var n="[a-zA-Z_:][a-zA-Z0-9:._-]*",s="[^\"'=<>`\\x00-\\x20]+",o="'[^']*'",i='"[^"]*"',a="(?:"+s+"|"+o+"|"+i+")",c="(?:\\s+"+n+"(?:\\s*=\\s*"+a+")?)",l="<[A-Za-z][A-Za-z0-9\\-]*"+c+"*\\s*\\/?>",u="<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>",p="<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->",h="<[?].*?[?]>",f="<![A-Z]+\\s+[^>]*>",d="<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",m=new RegExp("^(?:"+l+"|"+u+"|"+p+"|"+h+"|"+f+"|"+d+")"),_=new RegExp("^(?:"+l+"|"+u+")");r.exports.HTML_TAG_RE=m,r.exports.HTML_OPEN_CLOSE_TAG_RE=_},{}],4:[function(e,r,t){"use strict";function n(e){return Object.prototype.toString.call(e)}function s(e){return"[object String]"===n(e)}function o(e,r){return y.call(e,r)}function i(e){var r=Array.prototype.slice.call(arguments,1);return r.forEach(function(r){if(r){if("object"!=typeof r)throw new TypeError(r+"must be object");Object.keys(r).forEach(function(t){e[t]=r[t]})}}),e}function a(e,r,t){return[].concat(e.slice(0,r),t,e.slice(r+1))}function c(e){return!(e>=55296&&e<=57343)&&(!(e>=64976&&e<=65007)&&(65535!==(65535&e)&&65534!==(65535&e)&&(!(e>=0&&e<=8)&&(11!==e&&(!(e>=14&&e<=31)&&(!(e>=127&&e<=159)&&!(e>1114111)))))))}function l(e){if(e>65535){e-=65536;var r=55296+(e>>10),t=56320+(1023&e);return String.fromCharCode(r,t)}return String.fromCharCode(e)}function u(e,r){var t=0;return o(D,r)?D[r]:35===r.charCodeAt(0)&&w.test(r)&&(t="x"===r[1].toLowerCase()?parseInt(r.slice(2),16):parseInt(r.slice(1),10),c(t))?l(t):e}function p(e){return e.indexOf("\\")<0?e:e.replace(x,"$1")}function h(e){return e.indexOf("\\")<0&&e.indexOf("&")<0?e:e.replace(A,function(e,r,t){return r?r:u(e,t)})}function f(e){return S[e]}function d(e){return q.test(e)?e.replace(E,f):e}function m(e){return e.replace(F,"\\$&")}function _(e){switch(e){case 9:case 32:return!0}return!1}function g(e){if(e>=8192&&e<=8202)return!0;switch(e){case 9:case 10:case 11:case 12:case 13:case 32:case 160:case 5760:case 8239:case 8287:case 12288:return!0}return!1}function k(e){return z.test(e)}function b(e){switch(e){case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:case 42:case 43:case 44:case 45:case 46:case 47:case 58:case 59:case 60:case 61:case 62:case 63:case 64:case 91:case 92:case 93:case 94:case 95:case 96:case 123:case 124:case 125:case 126:return!0;default:return!1}}function v(e){return e.trim().replace(/\s+/g," ").toUpperCase()}var y=Object.prototype.hasOwnProperty,x=/\\([!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~])/g,C=/&([a-z#][a-z0-9]{1,31});/gi,A=new RegExp(x.source+"|"+C.source,"gi"),w=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i,D=e("./entities"),q=/[&<>"]/,E=/[&<>"]/g,S={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"},F=/[.?*+^$[\]\\(){}|-]/g,z=e("uc.micro/categories/P/regex");t.lib={},t.lib.mdurl=e("mdurl"),t.lib.ucmicro=e("uc.micro"),t.assign=i,t.isString=s,t.has=o,t.unescapeMd=p,t.unescapeAll=h,t.isValidEntityCode=c,t.fromCodePoint=l,t.escapeHtml=d,t.arrayReplaceAt=a,t.isSpace=_,t.isWhiteSpace=g,t.isMdAsciiPunct=b,t.isPunctChar=k,t.escapeRE=m,t.normalizeReference=v},{"./entities":1,mdurl:58,"uc.micro":65,"uc.micro/categories/P/regex":63}],5:[function(e,r,t){"use strict";t.parseLinkLabel=e("./parse_link_label"),t.parseLinkDestination=e("./parse_link_destination"),t.parseLinkTitle=e("./parse_link_title")},{"./parse_link_destination":6,"./parse_link_label":7,"./parse_link_title":8}],6:[function(e,r,t){"use strict";var n=e("../common/utils").isSpace,s=e("../common/utils").unescapeAll;r.exports=function(e,r,t){var o,i,a=0,c=r,l={ok:!1,pos:0,lines:0,str:""};if(60===e.charCodeAt(r)){for(r++;r<t;){if(o=e.charCodeAt(r),10===o||n(o))return l;if(62===o)return l.pos=r+1,l.str=s(e.slice(c+1,r)),l.ok=!0,l;92===o&&r+1<t?r+=2:r++}return l}for(i=0;r<t&&(o=e.charCodeAt(r),32!==o)&&!(o<32||127===o);)if(92===o&&r+1<t)r+=2;else{if(40===o&&(i++,i>1))break;if(41===o&&(i--,i<0))break;r++}return c===r?l:(l.str=s(e.slice(c,r)),l.lines=a,l.pos=r,l.ok=!0,l)}},{"../common/utils":4}],7:[function(e,r,t){"use strict";r.exports=function(e,r,t){var n,s,o,i,a=-1,c=e.posMax,l=e.pos;for(e.pos=r+1,n=1;e.pos<c;){if(o=e.src.charCodeAt(e.pos),93===o&&(n--,0===n)){s=!0;break}if(i=e.pos,e.md.inline.skipToken(e),91===o)if(i===e.pos-1)n++;else if(t)return e.pos=l,-1}return s&&(a=e.pos),e.pos=l,a}},{}],8:[function(e,r,t){"use strict";var n=e("../common/utils").unescapeAll;r.exports=function(e,r,t){var s,o,i=0,a=r,c={ok:!1,pos:0,lines:0,str:""};if(r>=t)return c;if(o=e.charCodeAt(r),34!==o&&39!==o&&40!==o)return c;for(r++,40===o&&(o=41);r<t;){if(s=e.charCodeAt(r),s===o)return c.pos=r+1,c.lines=i,c.str=n(e.slice(a+1,r)),c.ok=!0,c;10===s?i++:92===s&&r+1<t&&(r++,10===e.charCodeAt(r)&&i++),r++}return c}},{"../common/utils":4}],9:[function(e,r,t){"use strict";function n(e){var r=e.trim().toLowerCase();return!g.test(r)||!!k.test(r)}function s(e){var r=d.parse(e,!0);if(r.hostname&&(!r.protocol||b.indexOf(r.protocol)>=0))try{r.hostname=m.toASCII(r.hostname)}catch(e){}return d.encode(d.format(r))}function o(e){var r=d.parse(e,!0);if(r.hostname&&(!r.protocol||b.indexOf(r.protocol)>=0))try{r.hostname=m.toUnicode(r.hostname)}catch(e){}return d.decode(d.format(r))}function i(e,r){return this instanceof i?(r||a.isString(e)||(r=e||{},e="default"),this.inline=new h,this.block=new p,this.core=new u,this.renderer=new l,this.linkify=new f,this.validateLink=n,this.normalizeLink=s,this.normalizeLinkText=o,this.utils=a,this.helpers=c,this.options={},this.configure(e),void(r&&this.set(r))):new i(e,r)}var a=e("./common/utils"),c=e("./helpers"),l=e("./renderer"),u=e("./parser_core"),p=e("./parser_block"),h=e("./parser_inline"),f=e("linkify-it"),d=e("mdurl"),m=e("punycode"),_={default:e("./presets/default"),zero:e("./presets/zero"),commonmark:e("./presets/commonmark")},g=/^(vbscript|javascript|file|data):/,k=/^data:image\/(gif|png|jpeg|webp);/,b=["http:","https:","mailto:"];i.prototype.set=function(e){return a.assign(this.options,e),this},i.prototype.configure=function(e){var r,t=this;if(a.isString(e)&&(r=e,e=_[r],!e))throw new Error('Wrong `markdown-it` preset "'+r+'", check name');if(!e)throw new Error("Wrong `markdown-it` preset, can't be empty");return e.options&&t.set(e.options),e.components&&Object.keys(e.components).forEach(function(r){e.components[r].rules&&t[r].ruler.enableOnly(e.components[r].rules),e.components[r].rules2&&t[r].ruler2.enableOnly(e.components[r].rules2)}),this},i.prototype.enable=function(e,r){var t=[];Array.isArray(e)||(e=[e]),["core","block","inline"].forEach(function(r){t=t.concat(this[r].ruler.enable(e,!0))},this),t=t.concat(this.inline.ruler2.enable(e,!0));var n=e.filter(function(e){return t.indexOf(e)<0});if(n.length&&!r)throw new Error("MarkdownIt. Failed to enable unknown rule(s): "+n);return this},i.prototype.disable=function(e,r){var t=[];Array.isArray(e)||(e=[e]),["core","block","inline"].forEach(function(r){t=t.concat(this[r].ruler.disable(e,!0))},this),t=t.concat(this.inline.ruler2.disable(e,!0));var n=e.filter(function(e){return t.indexOf(e)<0});if(n.length&&!r)throw new Error("MarkdownIt. Failed to disable unknown rule(s): "+n);return this},i.prototype.use=function(e){var r=[this].concat(Array.prototype.slice.call(arguments,1));return e.apply(e,r),this},i.prototype.parse=function(e,r){var t=new this.core.State(e,this,r);return this.core.process(t),t.tokens},i.prototype.render=function(e,r){return r=r||{},this.renderer.render(this.parse(e,r),this.options,r)},i.prototype.parseInline=function(e,r){var t=new this.core.State(e,this,r);return t.inlineMode=!0,this.core.process(t),t.tokens},i.prototype.renderInline=function(e,r){return r=r||{},this.renderer.render(this.parseInline(e,r),this.options,r)},r.exports=i},{"./common/utils":4,"./helpers":5,"./parser_block":10,"./parser_core":11,"./parser_inline":12,"./presets/commonmark":13,"./presets/default":14,"./presets/zero":15,"./renderer":16,"linkify-it":53,mdurl:58,punycode:60}],10:[function(e,r,t){"use strict";function n(){this.ruler=new s;for(var e=0;e<o.length;e++)this.ruler.push(o[e][0],o[e][1],{alt:(o[e][2]||[]).slice()})}var s=e("./ruler"),o=[["table",e("./rules_block/table"),["paragraph","reference"]],["code",e("./rules_block/code")],["fence",e("./rules_block/fence"),["paragraph","reference","blockquote","list"]],["blockquote",e("./rules_block/blockquote"),["paragraph","reference","list"]],["hr",e("./rules_block/hr"),["paragraph","reference","blockquote","list"]],["list",e("./rules_block/list"),["paragraph","reference","blockquote"]],["reference",e("./rules_block/reference")],["heading",e("./rules_block/heading"),["paragraph","reference","blockquote"]],["lheading",e("./rules_block/lheading")],["html_block",e("./rules_block/html_block"),["paragraph","reference","blockquote"]],["paragraph",e("./rules_block/paragraph")]];n.prototype.tokenize=function(e,r,t){for(var n,s,o=this.ruler.getRules(""),i=o.length,a=r,c=!1,l=e.md.options.maxNesting;a<t&&(e.line=a=e.skipEmptyLines(a),!(a>=t))&&!(e.sCount[a]<e.blkIndent);){if(e.level>=l){e.line=t;break}for(s=0;s<i&&!(n=o[s](e,a,t,!1));s++);if(e.tight=!c,e.isEmpty(e.line-1)&&(c=!0),a=e.line,a<t&&e.isEmpty(a)){if(c=!0,a++,a<t&&"list"===e.parentType&&e.isEmpty(a))break;e.line=a}}},n.prototype.parse=function(e,r,t,n){var s;e&&(s=new this.State(e,r,t,n),this.tokenize(s,s.line,s.lineMax))},n.prototype.State=e("./rules_block/state_block"),r.exports=n},{"./ruler":17,"./rules_block/blockquote":18,"./rules_block/code":19,"./rules_block/fence":20,"./rules_block/heading":21,"./rules_block/hr":22,"./rules_block/html_block":23,"./rules_block/lheading":24,"./rules_block/list":25,"./rules_block/paragraph":26,"./rules_block/reference":27,"./rules_block/state_block":28,"./rules_block/table":29}],11:[function(e,r,t){"use strict";function n(){this.ruler=new s;for(var e=0;e<o.length;e++)this.ruler.push(o[e][0],o[e][1])}var s=e("./ruler"),o=[["normalize",e("./rules_core/normalize")],["block",e("./rules_core/block")],["inline",e("./rules_core/inline")],["linkify",e("./rules_core/linkify")],["replacements",e("./rules_core/replacements")],["smartquotes",e("./rules_core/smartquotes")]];n.prototype.process=function(e){var r,t,n;for(n=this.ruler.getRules(""),r=0,t=n.length;r<t;r++)n[r](e)},n.prototype.State=e("./rules_core/state_core"),r.exports=n},{"./ruler":17,"./rules_core/block":30,"./rules_core/inline":31,"./rules_core/linkify":32,"./rules_core/normalize":33,"./rules_core/replacements":34,"./rules_core/smartquotes":35,"./rules_core/state_core":36}],12:[function(e,r,t){"use strict";function n(){var e;for(this.ruler=new s,e=0;e<o.length;e++)this.ruler.push(o[e][0],o[e][1]);for(this.ruler2=new s,e=0;e<i.length;e++)this.ruler2.push(i[e][0],i[e][1])}var s=e("./ruler"),o=[["text",e("./rules_inline/text")],["newline",e("./rules_inline/newline")],["escape",e("./rules_inline/escape")],["backticks",e("./rules_inline/backticks")],["strikethrough",e("./rules_inline/strikethrough").tokenize],["emphasis",e("./rules_inline/emphasis").tokenize],["link",e("./rules_inline/link")],["image",e("./rules_inline/image")],["autolink",e("./rules_inline/autolink")],["html_inline",e("./rules_inline/html_inline")],["entity",e("./rules_inline/entity")]],i=[["balance_pairs",e("./rules_inline/balance_pairs")],["strikethrough",e("./rules_inline/strikethrough").postProcess],["emphasis",e("./rules_inline/emphasis").postProcess],["text_collapse",e("./rules_inline/text_collapse")]];n.prototype.skipToken=function(e){var r,t,n=e.pos,s=this.ruler.getRules(""),o=s.length,i=e.md.options.maxNesting,a=e.cache;if("undefined"!=typeof a[n])return void(e.pos=a[n]);if(e.level<i)for(t=0;t<o&&(e.level++,r=s[t](e,!0),e.level--,!r);t++);else e.pos=e.posMax;r||e.pos++,a[n]=e.pos},n.prototype.tokenize=function(e){for(var r,t,n=this.ruler.getRules(""),s=n.length,o=e.posMax,i=e.md.options.maxNesting;e.pos<o;){if(e.level<i)for(t=0;t<s&&!(r=n[t](e,!1));t++);if(r){if(e.pos>=o)break}else e.pending+=e.src[e.pos++]}e.pending&&e.pushPending()},n.prototype.parse=function(e,r,t,n){var s,o,i,a=new this.State(e,r,t,n);for(this.tokenize(a),o=this.ruler2.getRules(""),i=o.length,s=0;s<i;s++)o[s](a)},n.prototype.State=e("./rules_inline/state_inline"),r.exports=n},{"./ruler":17,"./rules_inline/autolink":37,"./rules_inline/backticks":38,"./rules_inline/balance_pairs":39,"./rules_inline/emphasis":40,"./rules_inline/entity":41,"./rules_inline/escape":42,"./rules_inline/html_inline":43,"./rules_inline/image":44,"./rules_inline/link":45,"./rules_inline/newline":46,"./rules_inline/state_inline":47,"./rules_inline/strikethrough":48,"./rules_inline/text":49,"./rules_inline/text_collapse":50}],13:[function(e,r,t){"use strict";r.exports={options:{html:!0,xhtmlOut:!0,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"\u201c\u201d\u2018\u2019",highlight:null,maxNesting:20},components:{core:{rules:["normalize","block","inline"]},block:{rules:["blockquote","code","fence","heading","hr","html_block","lheading","list","reference","paragraph"]},inline:{rules:["autolink","backticks","emphasis","entity","escape","html_inline","image","link","newline","text"],rules2:["balance_pairs","emphasis","text_collapse"]}}}},{}],14:[function(e,r,t){"use strict";r.exports={options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"\u201c\u201d\u2018\u2019",highlight:null,maxNesting:100},components:{core:{},block:{},inline:{}}}},{}],15:[function(e,r,t){"use strict";r.exports={options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"\u201c\u201d\u2018\u2019",highlight:null,maxNesting:20},components:{core:{rules:["normalize","block","inline"]},block:{rules:["paragraph"]},inline:{rules:["text"],rules2:["balance_pairs","text_collapse"]}}}},{}],16:[function(e,r,t){"use strict";function n(){this.rules=s({},a)}var s=e("./common/utils").assign,o=e("./common/utils").unescapeAll,i=e("./common/utils").escapeHtml,a={};a.code_inline=function(e,r,t,n,s){var o=e[r];return"<code"+s.renderAttrs(o)+">"+i(e[r].content)+"</code>"},a.code_block=function(e,r,t,n,s){var o=e[r];return"<pre"+s.renderAttrs(o)+"><code>"+i(e[r].content)+"</code></pre>\n"},a.fence=function(e,r,t,n,s){var a,c,l,u,p=e[r],h=p.info?o(p.info).trim():"",f="";return h&&(f=h.split(/\s+/g)[0]),a=t.highlight?t.highlight(p.content,f)||i(p.content):i(p.content),0===a.indexOf("<pre")?a+"\n":h?(c=p.attrIndex("class"),l=p.attrs?p.attrs.slice():[],c<0?l.push(["class",t.langPrefix+f]):l[c][1]+=" "+t.langPrefix+f,u={attrs:l},"<pre><code"+s.renderAttrs(u)+">"+a+"</code></pre>\n"):"<pre><code"+s.renderAttrs(p)+">"+a+"</code></pre>\n"},a.image=function(e,r,t,n,s){var o=e[r];return o.attrs[o.attrIndex("alt")][1]=s.renderInlineAsText(o.children,t,n),s.renderToken(e,r,t)},a.hardbreak=function(e,r,t){return t.xhtmlOut?"<br />\n":"<br>\n"},a.softbreak=function(e,r,t){return t.breaks?t.xhtmlOut?"<br />\n":"<br>\n":"\n"},a.text=function(e,r){return i(e[r].content)},a.html_block=function(e,r){return e[r].content},a.html_inline=function(e,r){return e[r].content},n.prototype.renderAttrs=function(e){var r,t,n;if(!e.attrs)return"";for(n="",r=0,t=e.attrs.length;r<t;r++)n+=" "+i(e.attrs[r][0])+'="'+i(e.attrs[r][1])+'"';return n},n.prototype.renderToken=function(e,r,t){var n,s="",o=!1,i=e[r];return i.hidden?"":(i.block&&i.nesting!==-1&&r&&e[r-1].hidden&&(s+="\n"),s+=(i.nesting===-1?"</":"<")+i.tag,s+=this.renderAttrs(i),0===i.nesting&&t.xhtmlOut&&(s+=" /"),i.block&&(o=!0,1===i.nesting&&r+1<e.length&&(n=e[r+1],"inline"===n.type||n.hidden?o=!1:n.nesting===-1&&n.tag===i.tag&&(o=!1))),s+=o?">\n":">")},n.prototype.renderInline=function(e,r,t){for(var n,s="",o=this.rules,i=0,a=e.length;i<a;i++)n=e[i].type,s+="undefined"!=typeof o[n]?o[n](e,i,r,t,this):this.renderToken(e,i,r);return s},n.prototype.renderInlineAsText=function(e,r,t){for(var n="",s=0,o=e.length;s<o;s++)"text"===e[s].type?n+=e[s].content:"image"===e[s].type&&(n+=this.renderInlineAsText(e[s].children,r,t));return n},n.prototype.render=function(e,r,t){var n,s,o,i="",a=this.rules;for(n=0,s=e.length;n<s;n++)o=e[n].type,i+="inline"===o?this.renderInline(e[n].children,r,t):"undefined"!=typeof a[o]?a[e[n].type](e,n,r,t,this):this.renderToken(e,n,r,t);return i},r.exports=n},{"./common/utils":4}],17:[function(e,r,t){"use strict";function n(){this.__rules__=[],this.__cache__=null}n.prototype.__find__=function(e){for(var r=0;r<this.__rules__.length;r++)if(this.__rules__[r].name===e)return r;return-1},n.prototype.__compile__=function(){var e=this,r=[""];e.__rules__.forEach(function(e){e.enabled&&e.alt.forEach(function(e){r.indexOf(e)<0&&r.push(e)})}),e.__cache__={},r.forEach(function(r){e.__cache__[r]=[],e.__rules__.forEach(function(t){t.enabled&&(r&&t.alt.indexOf(r)<0||e.__cache__[r].push(t.fn))})})},n.prototype.at=function(e,r,t){var n=this.__find__(e),s=t||{};if(n===-1)throw new Error("Parser rule not found: "+e);this.__rules__[n].fn=r,this.__rules__[n].alt=s.alt||[],this.__cache__=null},n.prototype.before=function(e,r,t,n){var s=this.__find__(e),o=n||{};if(s===-1)throw new Error("Parser rule not found: "+e);this.__rules__.splice(s,0,{name:r,enabled:!0,fn:t,alt:o.alt||[]}),this.__cache__=null},n.prototype.after=function(e,r,t,n){var s=this.__find__(e),o=n||{};if(s===-1)throw new Error("Parser rule not found: "+e);this.__rules__.splice(s+1,0,{name:r,enabled:!0,fn:t,alt:o.alt||[]}),this.__cache__=null},n.prototype.push=function(e,r,t){var n=t||{};this.__rules__.push({name:e,enabled:!0,fn:r,alt:n.alt||[]}),this.__cache__=null},n.prototype.enable=function(e,r){Array.isArray(e)||(e=[e]);var t=[];return e.forEach(function(e){var n=this.__find__(e);if(n<0){if(r)return;throw new Error("Rules manager: invalid rule name "+e)}this.__rules__[n].enabled=!0,t.push(e)},this),this.__cache__=null,t},n.prototype.enableOnly=function(e,r){Array.isArray(e)||(e=[e]),this.__rules__.forEach(function(e){e.enabled=!1}),this.enable(e,r)},n.prototype.disable=function(e,r){Array.isArray(e)||(e=[e]);var t=[];return e.forEach(function(e){var n=this.__find__(e);if(n<0){if(r)return;throw new Error("Rules manager: invalid rule name "+e)}this.__rules__[n].enabled=!1,t.push(e)},this),this.__cache__=null,t},n.prototype.getRules=function(e){return null===this.__cache__&&this.__compile__(),this.__cache__[e]||[]},r.exports=n},{}],18:[function(e,r,t){"use strict";var n=e("../common/utils").isSpace;r.exports=function(e,r,t,s){var o,i,a,c,l,u,p,h,f,d,m,_,g,k,b,v,y=e.bMarks[r]+e.tShift[r],x=e.eMarks[r];if(62!==e.src.charCodeAt(y++))return!1;if(s)return!0;for(32===e.src.charCodeAt(y)&&y++,u=e.blkIndent,e.blkIndent=0,f=d=e.sCount[r]+y-(e.bMarks[r]+e.tShift[r]),l=[e.bMarks[r]],e.bMarks[r]=y;y<x&&(m=e.src.charCodeAt(y),n(m));)9===m?d+=4-d%4:d++,y++;for(i=y>=x,c=[e.sCount[r]],e.sCount[r]=d-f,a=[e.tShift[r]],e.tShift[r]=y-e.bMarks[r],_=e.md.block.ruler.getRules("blockquote"),o=r+1;o<t&&!(e.sCount[o]<u)&&(y=e.bMarks[o]+e.tShift[o],x=e.eMarks[o],!(y>=x));o++)if(62!==e.src.charCodeAt(y++)){if(i)break;for(v=!1,k=0,b=_.length;k<b;k++)if(_[k](e,o,t,!0)){v=!0;break}if(v)break;l.push(e.bMarks[o]),a.push(e.tShift[o]),c.push(e.sCount[o]),e.sCount[o]=-1}else{for(32===e.src.charCodeAt(y)&&y++,f=d=e.sCount[o]+y-(e.bMarks[o]+e.tShift[o]),l.push(e.bMarks[o]),e.bMarks[o]=y;y<x&&(m=e.src.charCodeAt(y),n(m));)9===m?d+=4-d%4:d++,y++;i=y>=x,c.push(e.sCount[o]),e.sCount[o]=d-f,a.push(e.tShift[o]),e.tShift[o]=y-e.bMarks[o]}for(p=e.parentType,e.parentType="blockquote",g=e.push("blockquote_open","blockquote",1),g.markup=">",g.map=h=[r,0],e.md.block.tokenize(e,r,o),g=e.push("blockquote_close","blockquote",-1),g.markup=">",e.parentType=p,h[1]=e.line,k=0;k<a.length;k++)e.bMarks[k+r]=l[k],e.tShift[k+r]=a[k],e.sCount[k+r]=c[k];return e.blkIndent=u,!0}},{"../common/utils":4}],19:[function(e,r,t){"use strict";r.exports=function(e,r,t){var n,s,o,i=0;if(e.sCount[r]-e.blkIndent<4)return!1;for(s=n=r+1;n<t;)if(e.isEmpty(n)){if(i++,i>=2&&"list"===e.parentType)break;n++}else{if(i=0,!(e.sCount[n]-e.blkIndent>=4))break;n++,s=n}return e.line=s,o=e.push("code_block","code",0),o.content=e.getLines(r,s,4+e.blkIndent,!0),o.map=[r,e.line],!0}},{}],20:[function(e,r,t){"use strict";r.exports=function(e,r,t,n){var s,o,i,a,c,l,u,p=!1,h=e.bMarks[r]+e.tShift[r],f=e.eMarks[r];if(h+3>f)return!1;if(s=e.src.charCodeAt(h),126!==s&&96!==s)return!1;if(c=h,h=e.skipChars(h,s),o=h-c,o<3)return!1;if(u=e.src.slice(c,h),i=e.src.slice(h,f),i.indexOf("`")>=0)return!1;if(n)return!0;for(a=r;(a++,!(a>=t))&&(h=c=e.bMarks[a]+e.tShift[a],f=e.eMarks[a],!(h<f&&e.sCount[a]<e.blkIndent));)if(e.src.charCodeAt(h)===s&&!(e.sCount[a]-e.blkIndent>=4||(h=e.skipChars(h,s),h-c<o||(h=e.skipSpaces(h),h<f)))){p=!0;break}return o=e.sCount[r],e.line=a+(p?1:0),l=e.push("fence","code",0),l.info=i,l.content=e.getLines(r+1,a,o,!0),l.markup=u,l.map=[r,e.line],!0}},{}],21:[function(e,r,t){"use strict";var n=e("../common/utils").isSpace;r.exports=function(e,r,t,s){var o,i,a,c,l=e.bMarks[r]+e.tShift[r],u=e.eMarks[r];if(o=e.src.charCodeAt(l),35!==o||l>=u)return!1;for(i=1,o=e.src.charCodeAt(++l);35===o&&l<u&&i<=6;)i++,o=e.src.charCodeAt(++l);return!(i>6||l<u&&32!==o)&&(!!s||(u=e.skipSpacesBack(u,l),a=e.skipCharsBack(u,35,l),a>l&&n(e.src.charCodeAt(a-1))&&(u=a),e.line=r+1,c=e.push("heading_open","h"+String(i),1),c.markup="########".slice(0,i),c.map=[r,e.line],c=e.push("inline","",0),c.content=e.src.slice(l,u).trim(),c.map=[r,e.line],c.children=[],c=e.push("heading_close","h"+String(i),-1),c.markup="########".slice(0,i),!0))}},{"../common/utils":4}],22:[function(e,r,t){"use strict";var n=e("../common/utils").isSpace;r.exports=function(e,r,t,s){var o,i,a,c,l=e.bMarks[r]+e.tShift[r],u=e.eMarks[r];if(o=e.src.charCodeAt(l++),42!==o&&45!==o&&95!==o)return!1;for(i=1;l<u;){if(a=e.src.charCodeAt(l++),a!==o&&!n(a))return!1;a===o&&i++}return!(i<3)&&(!!s||(e.line=r+1,c=e.push("hr","hr",0),c.map=[r,e.line],c.markup=Array(i+1).join(String.fromCharCode(o)),!0))}},{"../common/utils":4}],23:[function(e,r,t){"use strict";var n=e("../common/html_blocks"),s=e("../common/html_re").HTML_OPEN_CLOSE_TAG_RE,o=[[/^<(script|pre|style)(?=(\s|>|$))/i,/<\/(script|pre|style)>/i,!0],[/^<!--/,/-->/,!0],[/^<\?/,/\?>/,!0],[/^<![A-Z]/,/>/,!0],[/^<!\[CDATA\[/,/\]\]>/,!0],[new RegExp("^</?("+n.join("|")+")(?=(\\s|/?>|$))","i"),/^$/,!0],[new RegExp(s.source+"\\s*$"),/^$/,!1]];r.exports=function(e,r,t,n){var s,i,a,c,l=e.bMarks[r]+e.tShift[r],u=e.eMarks[r];if(!e.md.options.html)return!1;if(60!==e.src.charCodeAt(l))return!1;for(c=e.src.slice(l,u),s=0;s<o.length&&!o[s][0].test(c);s++);if(s===o.length)return!1;if(n)return o[s][2];if(i=r+1,!o[s][1].test(c))for(;i<t&&!(e.sCount[i]<e.blkIndent);i++)if(l=e.bMarks[i]+e.tShift[i],u=e.eMarks[i],c=e.src.slice(l,u),o[s][1].test(c)){0!==c.length&&i++;break}return e.line=i,a=e.push("html_block","",0),a.map=[r,i],a.content=e.getLines(r,i,e.blkIndent,!0),!0}},{"../common/html_blocks":2,"../common/html_re":3}],24:[function(e,r,t){"use strict";r.exports=function(e,r,t){for(var n,s,o,i,a,c,l,u,p,h=r+1,f=e.md.block.ruler.getRules("paragraph");h<t&&!e.isEmpty(h);h++)if(!(e.sCount[h]-e.blkIndent>3)){if(e.sCount[h]>=e.blkIndent&&(c=e.bMarks[h]+e.tShift[h],l=e.eMarks[h],c<l&&(p=e.src.charCodeAt(c),(45===p||61===p)&&(c=e.skipChars(c,p),c=e.skipSpaces(c),c>=l)))){u=61===p?1:2;break}if(!(e.sCount[h]<0)){for(s=!1,o=0,i=f.length;o<i;o++)if(f[o](e,h,t,!0)){s=!0;break}if(s)break}}return!!u&&(n=e.getLines(r,h,e.blkIndent,!1).trim(),e.line=h+1,a=e.push("heading_open","h"+String(u),1),a.markup=String.fromCharCode(p),a.map=[r,e.line],a=e.push("inline","",0),a.content=n,a.map=[r,e.line-1],a.children=[],a=e.push("heading_close","h"+String(u),-1),a.markup=String.fromCharCode(p),!0)}},{}],25:[function(e,r,t){"use strict";function n(e,r){var t,n,s,o;return n=e.bMarks[r]+e.tShift[r],s=e.eMarks[r],t=e.src.charCodeAt(n++),42!==t&&45!==t&&43!==t?-1:n<s&&(o=e.src.charCodeAt(n),!i(o))?-1:n}function s(e,r){var t,n=e.bMarks[r]+e.tShift[r],s=n,o=e.eMarks[r];if(s+1>=o)return-1;if(t=e.src.charCodeAt(s++),t<48||t>57)return-1;for(;;){if(s>=o)return-1;t=e.src.charCodeAt(s++);{if(!(t>=48&&t<=57)){if(41===t||46===t)break;return-1}if(s-n>=10)return-1}}return s<o&&(t=e.src.charCodeAt(s),!i(t))?-1:s}function o(e,r){var t,n,s=e.level+2;for(t=r+2,n=e.tokens.length-2;t<n;t++)e.tokens[t].level===s&&"paragraph_open"===e.tokens[t].type&&(e.tokens[t+2].hidden=!0,e.tokens[t].hidden=!0,t+=2)}var i=e("../common/utils").isSpace;r.exports=function(e,r,t,a){var c,l,u,p,h,f,d,m,_,g,k,b,v,y,x,C,A,w,D,q,E,S,F,z,L,T,R,M,I=!0;if((k=s(e,r))>=0)w=!0;else{if(!((k=n(e,r))>=0))return!1;w=!1}if(A=e.src.charCodeAt(k-1),a)return!0;for(q=e.tokens.length,w?(g=e.bMarks[r]+e.tShift[r],C=Number(e.src.substr(g,k-g-1)),L=e.push("ordered_list_open","ol",1),1!==C&&(L.attrs=[["start",C]])):L=e.push("bullet_list_open","ul",1),L.map=S=[r,0],L.markup=String.fromCharCode(A),c=r,E=!1,z=e.md.block.ruler.getRules("list");c<t;){for(v=k,y=e.eMarks[c],l=u=e.sCount[c]+k-(e.bMarks[r]+e.tShift[r]);v<y&&(b=e.src.charCodeAt(v),i(b));)9===b?u+=4-u%4:u++,v++;if(D=v,x=D>=y?1:u-l,x>4&&(x=1),p=l+x,L=e.push("list_item_open","li",1),L.markup=String.fromCharCode(A),L.map=F=[r,0],f=e.blkIndent,m=e.tight,h=e.tShift[r],d=e.sCount[r],_=e.parentType,e.blkIndent=p,e.tight=!0,e.parentType="list",e.tShift[r]=D-e.bMarks[r],e.sCount[r]=u,D>=y&&e.isEmpty(r+1)?e.line=Math.min(e.line+2,t):e.md.block.tokenize(e,r,t,!0),e.tight&&!E||(I=!1),E=e.line-r>1&&e.isEmpty(e.line-1),e.blkIndent=f,e.tShift[r]=h,e.sCount[r]=d,e.tight=m,e.parentType=_,L=e.push("list_item_close","li",-1),L.markup=String.fromCharCode(A),c=r=e.line,F[1]=c,D=e.bMarks[r],c>=t)break;if(e.isEmpty(c))break;if(e.sCount[c]<e.blkIndent)break;for(M=!1,T=0,R=z.length;T<R;T++)if(z[T](e,c,t,!0)){M=!0;break}if(M)break;if(w){if(k=s(e,c),k<0)break}else if(k=n(e,c),k<0)break;if(A!==e.src.charCodeAt(k-1))break}return L=w?e.push("ordered_list_close","ol",-1):e.push("bullet_list_close","ul",-1),L.markup=String.fromCharCode(A),S[1]=c,e.line=c,I&&o(e,q),!0}},{"../common/utils":4}],26:[function(e,r,t){"use strict";r.exports=function(e,r){for(var t,n,s,o,i,a=r+1,c=e.md.block.ruler.getRules("paragraph"),l=e.lineMax;a<l&&!e.isEmpty(a);a++)if(!(e.sCount[a]-e.blkIndent>3||e.sCount[a]<0)){for(n=!1,s=0,o=c.length;s<o;s++)if(c[s](e,a,l,!0)){n=!0;break}if(n)break}return t=e.getLines(r,a,e.blkIndent,!1).trim(),e.line=a,i=e.push("paragraph_open","p",1),i.map=[r,e.line],i=e.push("inline","",0),i.content=t,i.map=[r,e.line],i.children=[],i=e.push("paragraph_close","p",-1),!0}},{}],27:[function(e,r,t){"use strict";var n=e("../helpers/parse_link_destination"),s=e("../helpers/parse_link_title"),o=e("../common/utils").normalizeReference,i=e("../common/utils").isSpace;r.exports=function(e,r,t,a){var c,l,u,p,h,f,d,m,_,g,k,b,v,y,x,C=0,A=e.bMarks[r]+e.tShift[r],w=e.eMarks[r],D=r+1;if(91!==e.src.charCodeAt(A))return!1;for(;++A<w;)if(93===e.src.charCodeAt(A)&&92!==e.src.charCodeAt(A-1)){if(A+1===w)return!1;if(58!==e.src.charCodeAt(A+1))return!1;break}for(p=e.lineMax,y=e.md.block.ruler.getRules("reference");D<p&&!e.isEmpty(D);D++)if(!(e.sCount[D]-e.blkIndent>3||e.sCount[D]<0)){for(v=!1,f=0,d=y.length;f<d;f++)if(y[f](e,D,p,!0)){v=!0;break}if(v)break}for(b=e.getLines(r,D,e.blkIndent,!1).trim(),w=b.length,A=1;A<w;A++){if(c=b.charCodeAt(A),91===c)return!1;if(93===c){_=A;break}10===c?C++:92===c&&(A++,A<w&&10===b.charCodeAt(A)&&C++)}if(_<0||58!==b.charCodeAt(_+1))return!1;for(A=_+2;A<w;A++)if(c=b.charCodeAt(A),10===c)C++;else if(!i(c))break;if(g=n(b,A,w),!g.ok)return!1;if(h=e.md.normalizeLink(g.str),!e.md.validateLink(h))return!1;for(A=g.pos,C+=g.lines,l=A,u=C,k=A;A<w;A++)if(c=b.charCodeAt(A),10===c)C++;else if(!i(c))break;for(g=s(b,A,w),A<w&&k!==A&&g.ok?(x=g.str,A=g.pos,C+=g.lines):(x="",A=l,C=u);A<w&&(c=b.charCodeAt(A),i(c));)A++;if(A<w&&10!==b.charCodeAt(A)&&x)for(x="",A=l,C=u;A<w&&(c=b.charCodeAt(A),i(c));)A++;return!(A<w&&10!==b.charCodeAt(A))&&(!!(m=o(b.slice(1,_)))&&(!!a||("undefined"==typeof e.env.references&&(e.env.references={}),"undefined"==typeof e.env.references[m]&&(e.env.references[m]={title:x,href:h}),e.line=r+C+1,!0)))}},{"../common/utils":4,"../helpers/parse_link_destination":6,"../helpers/parse_link_title":8}],28:[function(e,r,t){"use strict";function n(e,r,t,n){var s,i,a,c,l,u,p,h;for(this.src=e,this.md=r,this.env=t,this.tokens=n,this.bMarks=[],this.eMarks=[],this.tShift=[],this.sCount=[],this.blkIndent=0,this.line=0,this.lineMax=0,this.tight=!1,this.parentType="root",this.ddIndent=-1,this.level=0,this.result="",i=this.src,h=!1,a=c=u=p=0,l=i.length;c<l;c++){if(s=i.charCodeAt(c),!h){if(o(s)){u++,9===s?p+=4-p%4:p++;continue}h=!0}10!==s&&c!==l-1||(10!==s&&c++,this.bMarks.push(a),this.eMarks.push(c),this.tShift.push(u),this.sCount.push(p),h=!1,u=0,p=0,a=c+1)}this.bMarks.push(i.length),this.eMarks.push(i.length),this.tShift.push(0),this.sCount.push(0),this.lineMax=this.bMarks.length-1}var s=e("../token"),o=e("../common/utils").isSpace;n.prototype.push=function(e,r,t){var n=new s(e,r,t);return n.block=!0,t<0&&this.level--,n.level=this.level,t>0&&this.level++,this.tokens.push(n),n},n.prototype.isEmpty=function(e){return this.bMarks[e]+this.tShift[e]>=this.eMarks[e]},n.prototype.skipEmptyLines=function(e){for(var r=this.lineMax;e<r&&!(this.bMarks[e]+this.tShift[e]<this.eMarks[e]);e++);return e},n.prototype.skipSpaces=function(e){for(var r,t=this.src.length;e<t&&(r=this.src.charCodeAt(e),o(r));e++);return e},n.prototype.skipSpacesBack=function(e,r){if(e<=r)return e;for(;e>r;)if(!o(this.src.charCodeAt(--e)))return e+1;return e},n.prototype.skipChars=function(e,r){for(var t=this.src.length;e<t&&this.src.charCodeAt(e)===r;e++);return e},n.prototype.skipCharsBack=function(e,r,t){if(e<=t)return e;for(;e>t;)if(r!==this.src.charCodeAt(--e))return e+1;return e},n.prototype.getLines=function(e,r,t,n){var s,i,a,c,l,u,p,h=e;if(e>=r)return"";for(u=new Array(r-e),s=0;h<r;h++,s++){for(i=0,p=c=this.bMarks[h],l=h+1<r||n?this.eMarks[h]+1:this.eMarks[h];c<l&&i<t;){if(a=this.src.charCodeAt(c),o(a))9===a?i+=4-i%4:i++;else{if(!(c-p<this.tShift[h]))break;i++}c++}u[s]=this.src.slice(c,l)}return u.join("")},n.prototype.Token=s,r.exports=n},{"../common/utils":4,"../token":51}],29:[function(e,r,t){"use strict";function n(e,r){var t=e.bMarks[r]+e.blkIndent,n=e.eMarks[r];return e.src.substr(t,n-t)}function s(e){var r,t=[],n=0,s=e.length,o=0,i=0,a=!1,c=0;for(r=e.charCodeAt(n);n<s;)96===r&&o%2===0?(a=!a,c=n):124!==r||o%2!==0||a?92===r?o++:o=0:(t.push(e.substring(i,n)),i=n+1),n++,n===s&&a&&(a=!1,n=c+1),r=e.charCodeAt(n);return t.push(e.substring(i)),t}r.exports=function(e,r,t,o){var i,a,c,l,u,p,h,f,d,m,_,g;if(r+2>t)return!1;if(u=r+1,e.sCount[u]<e.blkIndent)return!1;if(c=e.bMarks[u]+e.tShift[u],c>=e.eMarks[u])return!1;if(i=e.src.charCodeAt(c),124!==i&&45!==i&&58!==i)return!1;if(a=n(e,r+1),!/^[-:| ]+$/.test(a))return!1;for(p=a.split("|"),d=[],l=0;l<p.length;l++){if(m=p[l].trim(),!m){if(0===l||l===p.length-1)continue;return!1;
}if(!/^:?-+:?$/.test(m))return!1;58===m.charCodeAt(m.length-1)?d.push(58===m.charCodeAt(0)?"center":"right"):58===m.charCodeAt(0)?d.push("left"):d.push("")}if(a=n(e,r).trim(),a.indexOf("|")===-1)return!1;if(p=s(a.replace(/^\||\|$/g,"")),h=p.length,h>d.length)return!1;if(o)return!0;for(f=e.push("table_open","table",1),f.map=_=[r,0],f=e.push("thead_open","thead",1),f.map=[r,r+1],f=e.push("tr_open","tr",1),f.map=[r,r+1],l=0;l<p.length;l++)f=e.push("th_open","th",1),f.map=[r,r+1],d[l]&&(f.attrs=[["style","text-align:"+d[l]]]),f=e.push("inline","",0),f.content=p[l].trim(),f.map=[r,r+1],f.children=[],f=e.push("th_close","th",-1);for(f=e.push("tr_close","tr",-1),f=e.push("thead_close","thead",-1),f=e.push("tbody_open","tbody",1),f.map=g=[r+2,0],u=r+2;u<t&&!(e.sCount[u]<e.blkIndent)&&(a=n(e,u),a.indexOf("|")!==-1);u++){for(p=s(a.replace(/^\||\|\s*$/g,"")),f=e.push("tr_open","tr",1),l=0;l<h;l++)f=e.push("td_open","td",1),d[l]&&(f.attrs=[["style","text-align:"+d[l]]]),f=e.push("inline","",0),f.content=p[l]?p[l].trim():"",f.children=[],f=e.push("td_close","td",-1);f=e.push("tr_close","tr",-1)}return f=e.push("tbody_close","tbody",-1),f=e.push("table_close","table",-1),_[1]=g[1]=u,e.line=u,!0}},{}],30:[function(e,r,t){"use strict";r.exports=function(e){var r;e.inlineMode?(r=new e.Token("inline","",0),r.content=e.src,r.map=[0,1],r.children=[],e.tokens.push(r)):e.md.block.parse(e.src,e.md,e.env,e.tokens)}},{}],31:[function(e,r,t){"use strict";r.exports=function(e){var r,t,n,s=e.tokens;for(t=0,n=s.length;t<n;t++)r=s[t],"inline"===r.type&&e.md.inline.parse(r.content,e.md,e.env,r.children)}},{}],32:[function(e,r,t){"use strict";function n(e){return/^<a[>\s]/i.test(e)}function s(e){return/^<\/a\s*>/i.test(e)}var o=e("../common/utils").arrayReplaceAt;r.exports=function(e){var r,t,i,a,c,l,u,p,h,f,d,m,_,g,k,b,v,y=e.tokens;if(e.md.options.linkify)for(t=0,i=y.length;t<i;t++)if("inline"===y[t].type&&e.md.linkify.pretest(y[t].content))for(a=y[t].children,_=0,r=a.length-1;r>=0;r--)if(l=a[r],"link_close"!==l.type){if("html_inline"===l.type&&(n(l.content)&&_>0&&_--,s(l.content)&&_++),!(_>0)&&"text"===l.type&&e.md.linkify.test(l.content)){for(h=l.content,v=e.md.linkify.match(h),u=[],m=l.level,d=0,p=0;p<v.length;p++)g=v[p].url,k=e.md.normalizeLink(g),e.md.validateLink(k)&&(b=v[p].text,b=v[p].schema?"mailto:"!==v[p].schema||/^mailto:/i.test(b)?e.md.normalizeLinkText(b):e.md.normalizeLinkText("mailto:"+b).replace(/^mailto:/,""):e.md.normalizeLinkText("http://"+b).replace(/^http:\/\//,""),f=v[p].index,f>d&&(c=new e.Token("text","",0),c.content=h.slice(d,f),c.level=m,u.push(c)),c=new e.Token("link_open","a",1),c.attrs=[["href",k]],c.level=m++,c.markup="linkify",c.info="auto",u.push(c),c=new e.Token("text","",0),c.content=b,c.level=m,u.push(c),c=new e.Token("link_close","a",-1),c.level=--m,c.markup="linkify",c.info="auto",u.push(c),d=v[p].lastIndex);d<h.length&&(c=new e.Token("text","",0),c.content=h.slice(d),c.level=m,u.push(c)),y[t].children=a=o(a,r,u)}}else for(r--;a[r].level!==l.level&&"link_open"!==a[r].type;)r--}},{"../common/utils":4}],33:[function(e,r,t){"use strict";var n=/\r[\n\u0085]?|[\u2424\u2028\u0085]/g,s=/\u0000/g;r.exports=function(e){var r;r=e.src.replace(n,"\n"),r=r.replace(s,"\ufffd"),e.src=r}},{}],34:[function(e,r,t){"use strict";function n(e,r){return l[r.toLowerCase()]}function s(e){var r,t,s=0;for(r=e.length-1;r>=0;r--)t=e[r],"text"!==t.type||s||(t.content=t.content.replace(c,n)),"link_open"===t.type&&"auto"===t.info&&s--,"link_close"===t.type&&"auto"===t.info&&s++}function o(e){var r,t,n=0;for(r=e.length-1;r>=0;r--)t=e[r],"text"!==t.type||n||i.test(t.content)&&(t.content=t.content.replace(/\+-/g,"\xb1").replace(/\.{2,}/g,"\u2026").replace(/([?!])\u2026/g,"$1..").replace(/([?!]){4,}/g,"$1$1$1").replace(/,{2,}/g,",").replace(/(^|[^-])---([^-]|$)/gm,"$1\u2014$2").replace(/(^|\s)--(\s|$)/gm,"$1\u2013$2").replace(/(^|[^-\s])--([^-\s]|$)/gm,"$1\u2013$2")),"link_open"===t.type&&"auto"===t.info&&n--,"link_close"===t.type&&"auto"===t.info&&n++}var i=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,a=/\((c|tm|r|p)\)/i,c=/\((c|tm|r|p)\)/gi,l={c:"\xa9",r:"\xae",p:"\xa7",tm:"\u2122"};r.exports=function(e){var r;if(e.md.options.typographer)for(r=e.tokens.length-1;r>=0;r--)"inline"===e.tokens[r].type&&(a.test(e.tokens[r].content)&&s(e.tokens[r].children),i.test(e.tokens[r].content)&&o(e.tokens[r].children))}},{}],35:[function(e,r,t){"use strict";function n(e,r,t){return e.substr(0,r)+t+e.substr(r+1)}function s(e,r){var t,s,c,p,h,f,d,m,_,g,k,b,v,y,x,C,A,w,D,q,E;for(D=[],t=0;t<e.length;t++){for(s=e[t],d=e[t].level,A=D.length-1;A>=0&&!(D[A].level<=d);A--);if(D.length=A+1,"text"===s.type){c=s.content,h=0,f=c.length;e:for(;h<f&&(l.lastIndex=h,p=l.exec(c));){if(x=C=!0,h=p.index+1,w="'"===p[0],_=32,p.index-1>=0)_=c.charCodeAt(p.index-1);else for(A=t-1;A>=0;A--)if("text"===e[A].type){_=e[A].content.charCodeAt(e[A].content.length-1);break}if(g=32,h<f)g=c.charCodeAt(h);else for(A=t+1;A<e.length;A++)if("text"===e[A].type){g=e[A].content.charCodeAt(0);break}if(k=a(_)||i(String.fromCharCode(_)),b=a(g)||i(String.fromCharCode(g)),v=o(_),y=o(g),y?x=!1:b&&(v||k||(x=!1)),v?C=!1:k&&(y||b||(C=!1)),34===g&&'"'===p[0]&&_>=48&&_<=57&&(C=x=!1),x&&C&&(x=!1,C=b),x||C){if(C)for(A=D.length-1;A>=0&&(m=D[A],!(D[A].level<d));A--)if(m.single===w&&D[A].level===d){m=D[A],w?(q=r.md.options.quotes[2],E=r.md.options.quotes[3]):(q=r.md.options.quotes[0],E=r.md.options.quotes[1]),s.content=n(s.content,p.index,E),e[m.token].content=n(e[m.token].content,m.pos,q),h+=E.length-1,m.token===t&&(h+=q.length-1),c=s.content,f=c.length,D.length=A;continue e}x?D.push({token:t,pos:p.index,single:w,level:d}):C&&w&&(s.content=n(s.content,p.index,u))}else w&&(s.content=n(s.content,p.index,u))}}}}var o=e("../common/utils").isWhiteSpace,i=e("../common/utils").isPunctChar,a=e("../common/utils").isMdAsciiPunct,c=/['"]/,l=/['"]/g,u="\u2019";r.exports=function(e){var r;if(e.md.options.typographer)for(r=e.tokens.length-1;r>=0;r--)"inline"===e.tokens[r].type&&c.test(e.tokens[r].content)&&s(e.tokens[r].children,e)}},{"../common/utils":4}],36:[function(e,r,t){"use strict";function n(e,r,t){this.src=e,this.env=t,this.tokens=[],this.inlineMode=!1,this.md=r}var s=e("../token");n.prototype.Token=s,r.exports=n},{"../token":51}],37:[function(e,r,t){"use strict";var n=/^<([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/,s=/^<([a-zA-Z][a-zA-Z0-9+.\-]{1,31}):([^<>\x00-\x20]*)>/;r.exports=function(e,r){var t,o,i,a,c,l,u=e.pos;return 60===e.src.charCodeAt(u)&&(t=e.src.slice(u),!(t.indexOf(">")<0)&&(s.test(t)?(o=t.match(s),a=o[0].slice(1,-1),c=e.md.normalizeLink(a),!!e.md.validateLink(c)&&(r||(l=e.push("link_open","a",1),l.attrs=[["href",c]],l.markup="autolink",l.info="auto",l=e.push("text","",0),l.content=e.md.normalizeLinkText(a),l=e.push("link_close","a",-1),l.markup="autolink",l.info="auto"),e.pos+=o[0].length,!0)):!!n.test(t)&&(i=t.match(n),a=i[0].slice(1,-1),c=e.md.normalizeLink("mailto:"+a),!!e.md.validateLink(c)&&(r||(l=e.push("link_open","a",1),l.attrs=[["href",c]],l.markup="autolink",l.info="auto",l=e.push("text","",0),l.content=e.md.normalizeLinkText(a),l=e.push("link_close","a",-1),l.markup="autolink",l.info="auto"),e.pos+=i[0].length,!0))))}},{}],38:[function(e,r,t){"use strict";r.exports=function(e,r){var t,n,s,o,i,a,c=e.pos,l=e.src.charCodeAt(c);if(96!==l)return!1;for(t=c,c++,n=e.posMax;c<n&&96===e.src.charCodeAt(c);)c++;for(s=e.src.slice(t,c),o=i=c;(o=e.src.indexOf("`",i))!==-1;){for(i=o+1;i<n&&96===e.src.charCodeAt(i);)i++;if(i-o===s.length)return r||(a=e.push("code_inline","code",0),a.markup=s,a.content=e.src.slice(c,o).replace(/[ \n]+/g," ").trim()),e.pos=i,!0}return r||(e.pending+=s),e.pos+=s.length,!0}},{}],39:[function(e,r,t){"use strict";r.exports=function(e){var r,t,n,s,o=e.delimiters,i=e.delimiters.length;for(r=0;r<i;r++)if(n=o[r],n.close)for(t=r-n.jump-1;t>=0;){if(s=o[t],s.open&&s.marker===n.marker&&s.end<0&&s.level===n.level){n.jump=r-t,n.open=!1,s.end=r,s.jump=0;break}t-=s.jump+1}}},{}],40:[function(e,r,t){"use strict";r.exports.tokenize=function(e,r){var t,n,s,o=e.pos,i=e.src.charCodeAt(o);if(r)return!1;if(95!==i&&42!==i)return!1;for(n=e.scanDelims(e.pos,42===i),t=0;t<n.length;t++)s=e.push("text","",0),s.content=String.fromCharCode(i),e.delimiters.push({marker:i,jump:t,token:e.tokens.length-1,level:e.level,end:-1,open:n.can_open,close:n.can_close});return e.pos+=n.length,!0},r.exports.postProcess=function(e){var r,t,n,s,o,i,a=e.delimiters,c=e.delimiters.length;for(r=0;r<c;r++)t=a[r],95!==t.marker&&42!==t.marker||t.end!==-1&&(n=a[t.end],i=r+1<c&&a[r+1].end===t.end-1&&a[r+1].token===t.token+1&&a[t.end-1].token===n.token-1&&a[r+1].marker===t.marker,o=String.fromCharCode(t.marker),s=e.tokens[t.token],s.type=i?"strong_open":"em_open",s.tag=i?"strong":"em",s.nesting=1,s.markup=i?o+o:o,s.content="",s=e.tokens[n.token],s.type=i?"strong_close":"em_close",s.tag=i?"strong":"em",s.nesting=-1,s.markup=i?o+o:o,s.content="",i&&(e.tokens[a[r+1].token].content="",e.tokens[a[t.end-1].token].content="",r++))}},{}],41:[function(e,r,t){"use strict";var n=e("../common/entities"),s=e("../common/utils").has,o=e("../common/utils").isValidEntityCode,i=e("../common/utils").fromCodePoint,a=/^&#((?:x[a-f0-9]{1,8}|[0-9]{1,8}));/i,c=/^&([a-z][a-z0-9]{1,31});/i;r.exports=function(e,r){var t,l,u,p=e.pos,h=e.posMax;if(38!==e.src.charCodeAt(p))return!1;if(p+1<h)if(t=e.src.charCodeAt(p+1),35===t){if(u=e.src.slice(p).match(a))return r||(l="x"===u[1][0].toLowerCase()?parseInt(u[1].slice(1),16):parseInt(u[1],10),e.pending+=i(o(l)?l:65533)),e.pos+=u[0].length,!0}else if(u=e.src.slice(p).match(c),u&&s(n,u[1]))return r||(e.pending+=n[u[1]]),e.pos+=u[0].length,!0;return r||(e.pending+="&"),e.pos++,!0}},{"../common/entities":1,"../common/utils":4}],42:[function(e,r,t){"use strict";for(var n=e("../common/utils").isSpace,s=[],o=0;o<256;o++)s.push(0);"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function(e){s[e.charCodeAt(0)]=1}),r.exports=function(e,r){var t,o=e.pos,i=e.posMax;if(92!==e.src.charCodeAt(o))return!1;if(o++,o<i){if(t=e.src.charCodeAt(o),t<256&&0!==s[t])return r||(e.pending+=e.src[o]),e.pos+=2,!0;if(10===t){for(r||e.push("hardbreak","br",0),o++;o<i&&(t=e.src.charCodeAt(o),n(t));)o++;return e.pos=o,!0}}return r||(e.pending+="\\"),e.pos++,!0}},{"../common/utils":4}],43:[function(e,r,t){"use strict";function n(e){var r=32|e;return r>=97&&r<=122}var s=e("../common/html_re").HTML_TAG_RE;r.exports=function(e,r){var t,o,i,a,c=e.pos;return!!e.md.options.html&&(i=e.posMax,!(60!==e.src.charCodeAt(c)||c+2>=i)&&(t=e.src.charCodeAt(c+1),!(33!==t&&63!==t&&47!==t&&!n(t))&&(!!(o=e.src.slice(c).match(s))&&(r||(a=e.push("html_inline","",0),a.content=e.src.slice(c,c+o[0].length)),e.pos+=o[0].length,!0))))}},{"../common/html_re":3}],44:[function(e,r,t){"use strict";var n=e("../helpers/parse_link_label"),s=e("../helpers/parse_link_destination"),o=e("../helpers/parse_link_title"),i=e("../common/utils").normalizeReference,a=e("../common/utils").isSpace;r.exports=function(e,r){var t,c,l,u,p,h,f,d,m,_,g,k,b,v="",y=e.pos,x=e.posMax;if(33!==e.src.charCodeAt(e.pos))return!1;if(91!==e.src.charCodeAt(e.pos+1))return!1;if(h=e.pos+2,p=n(e,e.pos+1,!1),p<0)return!1;if(f=p+1,f<x&&40===e.src.charCodeAt(f)){for(f++;f<x&&(c=e.src.charCodeAt(f),a(c)||10===c);f++);if(f>=x)return!1;for(b=f,m=s(e.src,f,e.posMax),m.ok&&(v=e.md.normalizeLink(m.str),e.md.validateLink(v)?f=m.pos:v=""),b=f;f<x&&(c=e.src.charCodeAt(f),a(c)||10===c);f++);if(m=o(e.src,f,e.posMax),f<x&&b!==f&&m.ok)for(_=m.str,f=m.pos;f<x&&(c=e.src.charCodeAt(f),a(c)||10===c);f++);else _="";if(f>=x||41!==e.src.charCodeAt(f))return e.pos=y,!1;f++}else{if("undefined"==typeof e.env.references)return!1;if(f<x&&91===e.src.charCodeAt(f)?(b=f+1,f=n(e,f),f>=0?u=e.src.slice(b,f++):f=p+1):f=p+1,u||(u=e.src.slice(h,p)),d=e.env.references[i(u)],!d)return e.pos=y,!1;v=d.href,_=d.title}return r||(l=e.src.slice(h,p),e.md.inline.parse(l,e.md,e.env,k=[]),g=e.push("image","img",0),g.attrs=t=[["src",v],["alt",""]],g.children=k,g.content=l,_&&t.push(["title",_])),e.pos=f,e.posMax=x,!0}},{"../common/utils":4,"../helpers/parse_link_destination":6,"../helpers/parse_link_label":7,"../helpers/parse_link_title":8}],45:[function(e,r,t){"use strict";var n=e("../helpers/parse_link_label"),s=e("../helpers/parse_link_destination"),o=e("../helpers/parse_link_title"),i=e("../common/utils").normalizeReference,a=e("../common/utils").isSpace;r.exports=function(e,r){var t,c,l,u,p,h,f,d,m,_,g="",k=e.pos,b=e.posMax,v=e.pos;if(91!==e.src.charCodeAt(e.pos))return!1;if(p=e.pos+1,u=n(e,e.pos,!0),u<0)return!1;if(h=u+1,h<b&&40===e.src.charCodeAt(h)){for(h++;h<b&&(c=e.src.charCodeAt(h),a(c)||10===c);h++);if(h>=b)return!1;for(v=h,f=s(e.src,h,e.posMax),f.ok&&(g=e.md.normalizeLink(f.str),e.md.validateLink(g)?h=f.pos:g=""),v=h;h<b&&(c=e.src.charCodeAt(h),a(c)||10===c);h++);if(f=o(e.src,h,e.posMax),h<b&&v!==h&&f.ok)for(m=f.str,h=f.pos;h<b&&(c=e.src.charCodeAt(h),a(c)||10===c);h++);else m="";if(h>=b||41!==e.src.charCodeAt(h))return e.pos=k,!1;h++}else{if("undefined"==typeof e.env.references)return!1;if(h<b&&91===e.src.charCodeAt(h)?(v=h+1,h=n(e,h),h>=0?l=e.src.slice(v,h++):h=u+1):h=u+1,l||(l=e.src.slice(p,u)),d=e.env.references[i(l)],!d)return e.pos=k,!1;g=d.href,m=d.title}return r||(e.pos=p,e.posMax=u,_=e.push("link_open","a",1),_.attrs=t=[["href",g]],m&&t.push(["title",m]),e.md.inline.tokenize(e),_=e.push("link_close","a",-1)),e.pos=h,e.posMax=b,!0}},{"../common/utils":4,"../helpers/parse_link_destination":6,"../helpers/parse_link_label":7,"../helpers/parse_link_title":8}],46:[function(e,r,t){"use strict";r.exports=function(e,r){var t,n,s=e.pos;if(10!==e.src.charCodeAt(s))return!1;for(t=e.pending.length-1,n=e.posMax,r||(t>=0&&32===e.pending.charCodeAt(t)?t>=1&&32===e.pending.charCodeAt(t-1)?(e.pending=e.pending.replace(/ +$/,""),e.push("hardbreak","br",0)):(e.pending=e.pending.slice(0,-1),e.push("softbreak","br",0)):e.push("softbreak","br",0)),s++;s<n&&32===e.src.charCodeAt(s);)s++;return e.pos=s,!0}},{}],47:[function(e,r,t){"use strict";function n(e,r,t,n){this.src=e,this.env=t,this.md=r,this.tokens=n,this.pos=0,this.posMax=this.src.length,this.level=0,this.pending="",this.pendingLevel=0,this.cache={},this.delimiters=[]}var s=e("../token"),o=e("../common/utils").isWhiteSpace,i=e("../common/utils").isPunctChar,a=e("../common/utils").isMdAsciiPunct;n.prototype.pushPending=function(){var e=new s("text","",0);return e.content=this.pending,e.level=this.pendingLevel,this.tokens.push(e),this.pending="",e},n.prototype.push=function(e,r,t){this.pending&&this.pushPending();var n=new s(e,r,t);return t<0&&this.level--,n.level=this.level,t>0&&this.level++,this.pendingLevel=this.level,this.tokens.push(n),n},n.prototype.scanDelims=function(e,r){var t,n,s,c,l,u,p,h,f,d=e,m=!0,_=!0,g=this.posMax,k=this.src.charCodeAt(e);for(t=e>0?this.src.charCodeAt(e-1):32;d<g&&this.src.charCodeAt(d)===k;)d++;return s=d-e,n=d<g?this.src.charCodeAt(d):32,p=a(t)||i(String.fromCharCode(t)),f=a(n)||i(String.fromCharCode(n)),u=o(t),h=o(n),h?m=!1:f&&(u||p||(m=!1)),u?_=!1:p&&(h||f||(_=!1)),r?(c=m,l=_):(c=m&&(!_||p),l=_&&(!m||f)),{can_open:c,can_close:l,length:s}},n.prototype.Token=s,r.exports=n},{"../common/utils":4,"../token":51}],48:[function(e,r,t){"use strict";r.exports.tokenize=function(e,r){var t,n,s,o,i,a=e.pos,c=e.src.charCodeAt(a);if(r)return!1;if(126!==c)return!1;if(n=e.scanDelims(e.pos,!0),o=n.length,i=String.fromCharCode(c),o<2)return!1;for(o%2&&(s=e.push("text","",0),s.content=i,o--),t=0;t<o;t+=2)s=e.push("text","",0),s.content=i+i,e.delimiters.push({marker:c,jump:t,token:e.tokens.length-1,level:e.level,end:-1,open:n.can_open,close:n.can_close});return e.pos+=n.length,!0},r.exports.postProcess=function(e){var r,t,n,s,o,i=[],a=e.delimiters,c=e.delimiters.length;for(r=0;r<c;r++)n=a[r],126===n.marker&&n.end!==-1&&(s=a[n.end],o=e.tokens[n.token],o.type="s_open",o.tag="s",o.nesting=1,o.markup="~~",o.content="",o=e.tokens[s.token],o.type="s_close",o.tag="s",o.nesting=-1,o.markup="~~",o.content="","text"===e.tokens[s.token-1].type&&"~"===e.tokens[s.token-1].content&&i.push(s.token-1));for(;i.length;){for(r=i.pop(),t=r+1;t<e.tokens.length&&"s_close"===e.tokens[t].type;)t++;t--,r!==t&&(o=e.tokens[t],e.tokens[t]=e.tokens[r],e.tokens[r]=o)}}},{}],49:[function(e,r,t){"use strict";function n(e){switch(e){case 10:case 33:case 35:case 36:case 37:case 38:case 42:case 43:case 45:case 58:case 60:case 61:case 62:case 64:case 91:case 92:case 93:case 94:case 95:case 96:case 123:case 125:case 126:return!0;default:return!1}}r.exports=function(e,r){for(var t=e.pos;t<e.posMax&&!n(e.src.charCodeAt(t));)t++;return t!==e.pos&&(r||(e.pending+=e.src.slice(e.pos,t)),e.pos=t,!0)}},{}],50:[function(e,r,t){"use strict";r.exports=function(e){var r,t,n=0,s=e.tokens,o=e.tokens.length;for(r=t=0;r<o;r++)n+=s[r].nesting,s[r].level=n,"text"===s[r].type&&r+1<o&&"text"===s[r+1].type?s[r+1].content=s[r].content+s[r+1].content:(r!==t&&(s[t]=s[r]),t++);r!==t&&(s.length=t)}},{}],51:[function(e,r,t){"use strict";function n(e,r,t){this.type=e,this.tag=r,this.attrs=null,this.map=null,this.nesting=t,this.level=0,this.children=null,this.content="",this.markup="",this.info="",this.meta=null,this.block=!1,this.hidden=!1}n.prototype.attrIndex=function(e){var r,t,n;if(!this.attrs)return-1;for(r=this.attrs,t=0,n=r.length;t<n;t++)if(r[t][0]===e)return t;return-1},n.prototype.attrPush=function(e){this.attrs?this.attrs.push(e):this.attrs=[e]},n.prototype.attrSet=function(e,r){var t=this.attrIndex(e),n=[e,r];t<0?this.attrPush(n):this.attrs[t]=n},n.prototype.attrGet=function(e){var r=this.attrIndex(e),t=null;return r>=0&&(t=this.attrs[r][1]),t},n.prototype.attrJoin=function(e,r){var t=this.attrIndex(e);t<0?this.attrPush([e,r]):this.attrs[t][1]=this.attrs[t][1]+" "+r},r.exports=n},{}],52:[function(e,r,t){r.exports={Aacute:"\xc1",aacute:"\xe1",Abreve:"\u0102",abreve:"\u0103",ac:"\u223e",acd:"\u223f",acE:"\u223e\u0333",Acirc:"\xc2",acirc:"\xe2",acute:"\xb4",Acy:"\u0410",acy:"\u0430",AElig:"\xc6",aelig:"\xe6",af:"\u2061",Afr:"\ud835\udd04",afr:"\ud835\udd1e",Agrave:"\xc0",agrave:"\xe0",alefsym:"\u2135",aleph:"\u2135",Alpha:"\u0391",alpha:"\u03b1",Amacr:"\u0100",amacr:"\u0101",amalg:"\u2a3f",amp:"&",AMP:"&",andand:"\u2a55",And:"\u2a53",and:"\u2227",andd:"\u2a5c",andslope:"\u2a58",andv:"\u2a5a",ang:"\u2220",ange:"\u29a4",angle:"\u2220",angmsdaa:"\u29a8",angmsdab:"\u29a9",angmsdac:"\u29aa",angmsdad:"\u29ab",angmsdae:"\u29ac",angmsdaf:"\u29ad",angmsdag:"\u29ae",angmsdah:"\u29af",angmsd:"\u2221",angrt:"\u221f",angrtvb:"\u22be",angrtvbd:"\u299d",angsph:"\u2222",angst:"\xc5",angzarr:"\u237c",Aogon:"\u0104",aogon:"\u0105",Aopf:"\ud835\udd38",aopf:"\ud835\udd52",apacir:"\u2a6f",ap:"\u2248",apE:"\u2a70",ape:"\u224a",apid:"\u224b",apos:"'",ApplyFunction:"\u2061",approx:"\u2248",approxeq:"\u224a",Aring:"\xc5",aring:"\xe5",Ascr:"\ud835\udc9c",ascr:"\ud835\udcb6",Assign:"\u2254",ast:"*",asymp:"\u2248",asympeq:"\u224d",Atilde:"\xc3",atilde:"\xe3",Auml:"\xc4",auml:"\xe4",awconint:"\u2233",awint:"\u2a11",backcong:"\u224c",backepsilon:"\u03f6",backprime:"\u2035",backsim:"\u223d",backsimeq:"\u22cd",Backslash:"\u2216",Barv:"\u2ae7",barvee:"\u22bd",barwed:"\u2305",Barwed:"\u2306",barwedge:"\u2305",bbrk:"\u23b5",bbrktbrk:"\u23b6",bcong:"\u224c",Bcy:"\u0411",bcy:"\u0431",bdquo:"\u201e",becaus:"\u2235",because:"\u2235",Because:"\u2235",bemptyv:"\u29b0",bepsi:"\u03f6",bernou:"\u212c",Bernoullis:"\u212c",Beta:"\u0392",beta:"\u03b2",beth:"\u2136",between:"\u226c",Bfr:"\ud835\udd05",bfr:"\ud835\udd1f",bigcap:"\u22c2",bigcirc:"\u25ef",bigcup:"\u22c3",bigodot:"\u2a00",bigoplus:"\u2a01",bigotimes:"\u2a02",bigsqcup:"\u2a06",bigstar:"\u2605",bigtriangledown:"\u25bd",bigtriangleup:"\u25b3",biguplus:"\u2a04",bigvee:"\u22c1",bigwedge:"\u22c0",bkarow:"\u290d",blacklozenge:"\u29eb",blacksquare:"\u25aa",blacktriangle:"\u25b4",blacktriangledown:"\u25be",blacktriangleleft:"\u25c2",blacktriangleright:"\u25b8",blank:"\u2423",blk12:"\u2592",blk14:"\u2591",blk34:"\u2593",block:"\u2588",bne:"=\u20e5",bnequiv:"\u2261\u20e5",bNot:"\u2aed",bnot:"\u2310",Bopf:"\ud835\udd39",bopf:"\ud835\udd53",bot:"\u22a5",bottom:"\u22a5",bowtie:"\u22c8",boxbox:"\u29c9",boxdl:"\u2510",boxdL:"\u2555",boxDl:"\u2556",boxDL:"\u2557",boxdr:"\u250c",boxdR:"\u2552",boxDr:"\u2553",boxDR:"\u2554",boxh:"\u2500",boxH:"\u2550",boxhd:"\u252c",boxHd:"\u2564",boxhD:"\u2565",boxHD:"\u2566",boxhu:"\u2534",boxHu:"\u2567",boxhU:"\u2568",boxHU:"\u2569",boxminus:"\u229f",boxplus:"\u229e",boxtimes:"\u22a0",boxul:"\u2518",boxuL:"\u255b",boxUl:"\u255c",boxUL:"\u255d",boxur:"\u2514",boxuR:"\u2558",boxUr:"\u2559",boxUR:"\u255a",boxv:"\u2502",boxV:"\u2551",boxvh:"\u253c",boxvH:"\u256a",boxVh:"\u256b",boxVH:"\u256c",boxvl:"\u2524",boxvL:"\u2561",boxVl:"\u2562",boxVL:"\u2563",boxvr:"\u251c",boxvR:"\u255e",boxVr:"\u255f",boxVR:"\u2560",bprime:"\u2035",breve:"\u02d8",Breve:"\u02d8",brvbar:"\xa6",bscr:"\ud835\udcb7",Bscr:"\u212c",bsemi:"\u204f",bsim:"\u223d",bsime:"\u22cd",bsolb:"\u29c5",bsol:"\\",bsolhsub:"\u27c8",bull:"\u2022",bullet:"\u2022",bump:"\u224e",bumpE:"\u2aae",bumpe:"\u224f",Bumpeq:"\u224e",bumpeq:"\u224f",Cacute:"\u0106",cacute:"\u0107",capand:"\u2a44",capbrcup:"\u2a49",capcap:"\u2a4b",cap:"\u2229",Cap:"\u22d2",capcup:"\u2a47",capdot:"\u2a40",CapitalDifferentialD:"\u2145",caps:"\u2229\ufe00",caret:"\u2041",caron:"\u02c7",Cayleys:"\u212d",ccaps:"\u2a4d",Ccaron:"\u010c",ccaron:"\u010d",Ccedil:"\xc7",ccedil:"\xe7",Ccirc:"\u0108",ccirc:"\u0109",Cconint:"\u2230",ccups:"\u2a4c",ccupssm:"\u2a50",Cdot:"\u010a",cdot:"\u010b",cedil:"\xb8",Cedilla:"\xb8",cemptyv:"\u29b2",cent:"\xa2",centerdot:"\xb7",CenterDot:"\xb7",cfr:"\ud835\udd20",Cfr:"\u212d",CHcy:"\u0427",chcy:"\u0447",check:"\u2713",checkmark:"\u2713",Chi:"\u03a7",chi:"\u03c7",circ:"\u02c6",circeq:"\u2257",circlearrowleft:"\u21ba",circlearrowright:"\u21bb",circledast:"\u229b",circledcirc:"\u229a",circleddash:"\u229d",CircleDot:"\u2299",circledR:"\xae",circledS:"\u24c8",CircleMinus:"\u2296",CirclePlus:"\u2295",CircleTimes:"\u2297",cir:"\u25cb",cirE:"\u29c3",cire:"\u2257",cirfnint:"\u2a10",cirmid:"\u2aef",cirscir:"\u29c2",ClockwiseContourIntegral:"\u2232",CloseCurlyDoubleQuote:"\u201d",CloseCurlyQuote:"\u2019",clubs:"\u2663",clubsuit:"\u2663",colon:":",Colon:"\u2237",Colone:"\u2a74",colone:"\u2254",coloneq:"\u2254",comma:",",commat:"@",comp:"\u2201",compfn:"\u2218",complement:"\u2201",complexes:"\u2102",cong:"\u2245",congdot:"\u2a6d",Congruent:"\u2261",conint:"\u222e",Conint:"\u222f",ContourIntegral:"\u222e",copf:"\ud835\udd54",Copf:"\u2102",coprod:"\u2210",Coproduct:"\u2210",copy:"\xa9",COPY:"\xa9",copysr:"\u2117",CounterClockwiseContourIntegral:"\u2233",crarr:"\u21b5",cross:"\u2717",Cross:"\u2a2f",Cscr:"\ud835\udc9e",cscr:"\ud835\udcb8",csub:"\u2acf",csube:"\u2ad1",csup:"\u2ad0",csupe:"\u2ad2",ctdot:"\u22ef",cudarrl:"\u2938",cudarrr:"\u2935",cuepr:"\u22de",cuesc:"\u22df",cularr:"\u21b6",cularrp:"\u293d",cupbrcap:"\u2a48",cupcap:"\u2a46",CupCap:"\u224d",cup:"\u222a",Cup:"\u22d3",cupcup:"\u2a4a",cupdot:"\u228d",cupor:"\u2a45",cups:"\u222a\ufe00",curarr:"\u21b7",curarrm:"\u293c",curlyeqprec:"\u22de",curlyeqsucc:"\u22df",curlyvee:"\u22ce",curlywedge:"\u22cf",curren:"\xa4",curvearrowleft:"\u21b6",curvearrowright:"\u21b7",cuvee:"\u22ce",cuwed:"\u22cf",cwconint:"\u2232",cwint:"\u2231",cylcty:"\u232d",dagger:"\u2020",Dagger:"\u2021",daleth:"\u2138",darr:"\u2193",Darr:"\u21a1",dArr:"\u21d3",dash:"\u2010",Dashv:"\u2ae4",dashv:"\u22a3",dbkarow:"\u290f",dblac:"\u02dd",Dcaron:"\u010e",dcaron:"\u010f",Dcy:"\u0414",dcy:"\u0434",ddagger:"\u2021",ddarr:"\u21ca",DD:"\u2145",dd:"\u2146",DDotrahd:"\u2911",ddotseq:"\u2a77",deg:"\xb0",Del:"\u2207",Delta:"\u0394",delta:"\u03b4",demptyv:"\u29b1",dfisht:"\u297f",Dfr:"\ud835\udd07",dfr:"\ud835\udd21",dHar:"\u2965",dharl:"\u21c3",dharr:"\u21c2",DiacriticalAcute:"\xb4",DiacriticalDot:"\u02d9",DiacriticalDoubleAcute:"\u02dd",DiacriticalGrave:"`",DiacriticalTilde:"\u02dc",diam:"\u22c4",diamond:"\u22c4",Diamond:"\u22c4",diamondsuit:"\u2666",diams:"\u2666",die:"\xa8",DifferentialD:"\u2146",digamma:"\u03dd",disin:"\u22f2",div:"\xf7",divide:"\xf7",divideontimes:"\u22c7",divonx:"\u22c7",DJcy:"\u0402",djcy:"\u0452",dlcorn:"\u231e",dlcrop:"\u230d",dollar:"$",Dopf:"\ud835\udd3b",dopf:"\ud835\udd55",Dot:"\xa8",dot:"\u02d9",DotDot:"\u20dc",doteq:"\u2250",doteqdot:"\u2251",DotEqual:"\u2250",dotminus:"\u2238",dotplus:"\u2214",dotsquare:"\u22a1",doublebarwedge:"\u2306",DoubleContourIntegral:"\u222f",DoubleDot:"\xa8",DoubleDownArrow:"\u21d3",DoubleLeftArrow:"\u21d0",DoubleLeftRightArrow:"\u21d4",DoubleLeftTee:"\u2ae4",DoubleLongLeftArrow:"\u27f8",DoubleLongLeftRightArrow:"\u27fa",DoubleLongRightArrow:"\u27f9",DoubleRightArrow:"\u21d2",DoubleRightTee:"\u22a8",DoubleUpArrow:"\u21d1",DoubleUpDownArrow:"\u21d5",DoubleVerticalBar:"\u2225",DownArrowBar:"\u2913",downarrow:"\u2193",DownArrow:"\u2193",Downarrow:"\u21d3",DownArrowUpArrow:"\u21f5",DownBreve:"\u0311",downdownarrows:"\u21ca",downharpoonleft:"\u21c3",downharpoonright:"\u21c2",DownLeftRightVector:"\u2950",DownLeftTeeVector:"\u295e",DownLeftVectorBar:"\u2956",DownLeftVector:"\u21bd",DownRightTeeVector:"\u295f",DownRightVectorBar:"\u2957",DownRightVector:"\u21c1",DownTeeArrow:"\u21a7",DownTee:"\u22a4",drbkarow:"\u2910",drcorn:"\u231f",drcrop:"\u230c",Dscr:"\ud835\udc9f",dscr:"\ud835\udcb9",DScy:"\u0405",dscy:"\u0455",dsol:"\u29f6",Dstrok:"\u0110",dstrok:"\u0111",dtdot:"\u22f1",dtri:"\u25bf",dtrif:"\u25be",duarr:"\u21f5",duhar:"\u296f",dwangle:"\u29a6",DZcy:"\u040f",dzcy:"\u045f",dzigrarr:"\u27ff",Eacute:"\xc9",eacute:"\xe9",easter:"\u2a6e",Ecaron:"\u011a",ecaron:"\u011b",Ecirc:"\xca",ecirc:"\xea",ecir:"\u2256",ecolon:"\u2255",Ecy:"\u042d",ecy:"\u044d",eDDot:"\u2a77",Edot:"\u0116",edot:"\u0117",eDot:"\u2251",ee:"\u2147",efDot:"\u2252",Efr:"\ud835\udd08",efr:"\ud835\udd22",eg:"\u2a9a",Egrave:"\xc8",egrave:"\xe8",egs:"\u2a96",egsdot:"\u2a98",el:"\u2a99",Element:"\u2208",elinters:"\u23e7",ell:"\u2113",els:"\u2a95",elsdot:"\u2a97",Emacr:"\u0112",emacr:"\u0113",empty:"\u2205",emptyset:"\u2205",EmptySmallSquare:"\u25fb",emptyv:"\u2205",EmptyVerySmallSquare:"\u25ab",emsp13:"\u2004",emsp14:"\u2005",emsp:"\u2003",ENG:"\u014a",eng:"\u014b",ensp:"\u2002",Eogon:"\u0118",eogon:"\u0119",Eopf:"\ud835\udd3c",eopf:"\ud835\udd56",epar:"\u22d5",eparsl:"\u29e3",eplus:"\u2a71",epsi:"\u03b5",Epsilon:"\u0395",epsilon:"\u03b5",epsiv:"\u03f5",eqcirc:"\u2256",eqcolon:"\u2255",eqsim:"\u2242",eqslantgtr:"\u2a96",eqslantless:"\u2a95",Equal:"\u2a75",equals:"=",EqualTilde:"\u2242",equest:"\u225f",Equilibrium:"\u21cc",equiv:"\u2261",equivDD:"\u2a78",eqvparsl:"\u29e5",erarr:"\u2971",erDot:"\u2253",escr:"\u212f",Escr:"\u2130",esdot:"\u2250",Esim:"\u2a73",esim:"\u2242",Eta:"\u0397",eta:"\u03b7",ETH:"\xd0",eth:"\xf0",Euml:"\xcb",euml:"\xeb",euro:"\u20ac",excl:"!",exist:"\u2203",Exists:"\u2203",expectation:"\u2130",exponentiale:"\u2147",ExponentialE:"\u2147",fallingdotseq:"\u2252",Fcy:"\u0424",fcy:"\u0444",female:"\u2640",ffilig:"\ufb03",fflig:"\ufb00",ffllig:"\ufb04",Ffr:"\ud835\udd09",ffr:"\ud835\udd23",filig:"\ufb01",FilledSmallSquare:"\u25fc",FilledVerySmallSquare:"\u25aa",fjlig:"fj",flat:"\u266d",fllig:"\ufb02",fltns:"\u25b1",fnof:"\u0192",Fopf:"\ud835\udd3d",fopf:"\ud835\udd57",forall:"\u2200",ForAll:"\u2200",fork:"\u22d4",forkv:"\u2ad9",Fouriertrf:"\u2131",fpartint:"\u2a0d",frac12:"\xbd",frac13:"\u2153",frac14:"\xbc",frac15:"\u2155",frac16:"\u2159",frac18:"\u215b",frac23:"\u2154",frac25:"\u2156",frac34:"\xbe",frac35:"\u2157",frac38:"\u215c",frac45:"\u2158",frac56:"\u215a",frac58:"\u215d",frac78:"\u215e",frasl:"\u2044",frown:"\u2322",fscr:"\ud835\udcbb",Fscr:"\u2131",gacute:"\u01f5",Gamma:"\u0393",gamma:"\u03b3",Gammad:"\u03dc",gammad:"\u03dd",gap:"\u2a86",Gbreve:"\u011e",gbreve:"\u011f",Gcedil:"\u0122",Gcirc:"\u011c",gcirc:"\u011d",Gcy:"\u0413",gcy:"\u0433",Gdot:"\u0120",gdot:"\u0121",ge:"\u2265",gE:"\u2267",gEl:"\u2a8c",gel:"\u22db",geq:"\u2265",geqq:"\u2267",geqslant:"\u2a7e",gescc:"\u2aa9",ges:"\u2a7e",gesdot:"\u2a80",gesdoto:"\u2a82",gesdotol:"\u2a84",gesl:"\u22db\ufe00",gesles:"\u2a94",Gfr:"\ud835\udd0a",gfr:"\ud835\udd24",gg:"\u226b",Gg:"\u22d9",ggg:"\u22d9",gimel:"\u2137",GJcy:"\u0403",gjcy:"\u0453",gla:"\u2aa5",gl:"\u2277",glE:"\u2a92",glj:"\u2aa4",gnap:"\u2a8a",gnapprox:"\u2a8a",gne:"\u2a88",gnE:"\u2269",gneq:"\u2a88",gneqq:"\u2269",gnsim:"\u22e7",Gopf:"\ud835\udd3e",gopf:"\ud835\udd58",grave:"`",GreaterEqual:"\u2265",GreaterEqualLess:"\u22db",GreaterFullEqual:"\u2267",GreaterGreater:"\u2aa2",GreaterLess:"\u2277",GreaterSlantEqual:"\u2a7e",GreaterTilde:"\u2273",Gscr:"\ud835\udca2",gscr:"\u210a",gsim:"\u2273",gsime:"\u2a8e",gsiml:"\u2a90",gtcc:"\u2aa7",gtcir:"\u2a7a",gt:">",GT:">",Gt:"\u226b",gtdot:"\u22d7",gtlPar:"\u2995",gtquest:"\u2a7c",gtrapprox:"\u2a86",gtrarr:"\u2978",gtrdot:"\u22d7",gtreqless:"\u22db",gtreqqless:"\u2a8c",gtrless:"\u2277",gtrsim:"\u2273",gvertneqq:"\u2269\ufe00",gvnE:"\u2269\ufe00",Hacek:"\u02c7",hairsp:"\u200a",half:"\xbd",hamilt:"\u210b",HARDcy:"\u042a",hardcy:"\u044a",harrcir:"\u2948",harr:"\u2194",hArr:"\u21d4",harrw:"\u21ad",Hat:"^",hbar:"\u210f",Hcirc:"\u0124",hcirc:"\u0125",hearts:"\u2665",heartsuit:"\u2665",hellip:"\u2026",hercon:"\u22b9",hfr:"\ud835\udd25",Hfr:"\u210c",HilbertSpace:"\u210b",hksearow:"\u2925",hkswarow:"\u2926",hoarr:"\u21ff",homtht:"\u223b",hookleftarrow:"\u21a9",hookrightarrow:"\u21aa",hopf:"\ud835\udd59",Hopf:"\u210d",horbar:"\u2015",HorizontalLine:"\u2500",hscr:"\ud835\udcbd",Hscr:"\u210b",hslash:"\u210f",Hstrok:"\u0126",hstrok:"\u0127",HumpDownHump:"\u224e",HumpEqual:"\u224f",hybull:"\u2043",hyphen:"\u2010",Iacute:"\xcd",iacute:"\xed",ic:"\u2063",Icirc:"\xce",icirc:"\xee",Icy:"\u0418",icy:"\u0438",Idot:"\u0130",IEcy:"\u0415",iecy:"\u0435",iexcl:"\xa1",iff:"\u21d4",ifr:"\ud835\udd26",Ifr:"\u2111",Igrave:"\xcc",igrave:"\xec",ii:"\u2148",iiiint:"\u2a0c",iiint:"\u222d",iinfin:"\u29dc",iiota:"\u2129",IJlig:"\u0132",ijlig:"\u0133",Imacr:"\u012a",imacr:"\u012b",image:"\u2111",ImaginaryI:"\u2148",imagline:"\u2110",imagpart:"\u2111",imath:"\u0131",Im:"\u2111",imof:"\u22b7",imped:"\u01b5",Implies:"\u21d2",incare:"\u2105",in:"\u2208",infin:"\u221e",infintie:"\u29dd",inodot:"\u0131",intcal:"\u22ba",int:"\u222b",Int:"\u222c",integers:"\u2124",Integral:"\u222b",intercal:"\u22ba",Intersection:"\u22c2",intlarhk:"\u2a17",intprod:"\u2a3c",InvisibleComma:"\u2063",InvisibleTimes:"\u2062",IOcy:"\u0401",iocy:"\u0451",Iogon:"\u012e",iogon:"\u012f",Iopf:"\ud835\udd40",iopf:"\ud835\udd5a",Iota:"\u0399",iota:"\u03b9",iprod:"\u2a3c",iquest:"\xbf",iscr:"\ud835\udcbe",Iscr:"\u2110",isin:"\u2208",isindot:"\u22f5",isinE:"\u22f9",isins:"\u22f4",isinsv:"\u22f3",isinv:"\u2208",it:"\u2062",Itilde:"\u0128",itilde:"\u0129",Iukcy:"\u0406",iukcy:"\u0456",Iuml:"\xcf",iuml:"\xef",Jcirc:"\u0134",jcirc:"\u0135",Jcy:"\u0419",jcy:"\u0439",Jfr:"\ud835\udd0d",jfr:"\ud835\udd27",jmath:"\u0237",Jopf:"\ud835\udd41",jopf:"\ud835\udd5b",Jscr:"\ud835\udca5",jscr:"\ud835\udcbf",Jsercy:"\u0408",jsercy:"\u0458",Jukcy:"\u0404",jukcy:"\u0454",Kappa:"\u039a",kappa:"\u03ba",kappav:"\u03f0",Kcedil:"\u0136",kcedil:"\u0137",Kcy:"\u041a",kcy:"\u043a",Kfr:"\ud835\udd0e",kfr:"\ud835\udd28",kgreen:"\u0138",KHcy:"\u0425",khcy:"\u0445",KJcy:"\u040c",kjcy:"\u045c",Kopf:"\ud835\udd42",kopf:"\ud835\udd5c",Kscr:"\ud835\udca6",kscr:"\ud835\udcc0",lAarr:"\u21da",Lacute:"\u0139",lacute:"\u013a",laemptyv:"\u29b4",lagran:"\u2112",Lambda:"\u039b",lambda:"\u03bb",lang:"\u27e8",Lang:"\u27ea",langd:"\u2991",langle:"\u27e8",lap:"\u2a85",Laplacetrf:"\u2112",laquo:"\xab",larrb:"\u21e4",larrbfs:"\u291f",larr:"\u2190",Larr:"\u219e",lArr:"\u21d0",larrfs:"\u291d",larrhk:"\u21a9",larrlp:"\u21ab",larrpl:"\u2939",larrsim:"\u2973",larrtl:"\u21a2",latail:"\u2919",lAtail:"\u291b",lat:"\u2aab",late:"\u2aad",lates:"\u2aad\ufe00",lbarr:"\u290c",lBarr:"\u290e",lbbrk:"\u2772",lbrace:"{",lbrack:"[",lbrke:"\u298b",lbrksld:"\u298f",lbrkslu:"\u298d",Lcaron:"\u013d",lcaron:"\u013e",Lcedil:"\u013b",lcedil:"\u013c",lceil:"\u2308",lcub:"{",Lcy:"\u041b",lcy:"\u043b",ldca:"\u2936",ldquo:"\u201c",ldquor:"\u201e",ldrdhar:"\u2967",ldrushar:"\u294b",ldsh:"\u21b2",le:"\u2264",lE:"\u2266",LeftAngleBracket:"\u27e8",
LeftArrowBar:"\u21e4",leftarrow:"\u2190",LeftArrow:"\u2190",Leftarrow:"\u21d0",LeftArrowRightArrow:"\u21c6",leftarrowtail:"\u21a2",LeftCeiling:"\u2308",LeftDoubleBracket:"\u27e6",LeftDownTeeVector:"\u2961",LeftDownVectorBar:"\u2959",LeftDownVector:"\u21c3",LeftFloor:"\u230a",leftharpoondown:"\u21bd",leftharpoonup:"\u21bc",leftleftarrows:"\u21c7",leftrightarrow:"\u2194",LeftRightArrow:"\u2194",Leftrightarrow:"\u21d4",leftrightarrows:"\u21c6",leftrightharpoons:"\u21cb",leftrightsquigarrow:"\u21ad",LeftRightVector:"\u294e",LeftTeeArrow:"\u21a4",LeftTee:"\u22a3",LeftTeeVector:"\u295a",leftthreetimes:"\u22cb",LeftTriangleBar:"\u29cf",LeftTriangle:"\u22b2",LeftTriangleEqual:"\u22b4",LeftUpDownVector:"\u2951",LeftUpTeeVector:"\u2960",LeftUpVectorBar:"\u2958",LeftUpVector:"\u21bf",LeftVectorBar:"\u2952",LeftVector:"\u21bc",lEg:"\u2a8b",leg:"\u22da",leq:"\u2264",leqq:"\u2266",leqslant:"\u2a7d",lescc:"\u2aa8",les:"\u2a7d",lesdot:"\u2a7f",lesdoto:"\u2a81",lesdotor:"\u2a83",lesg:"\u22da\ufe00",lesges:"\u2a93",lessapprox:"\u2a85",lessdot:"\u22d6",lesseqgtr:"\u22da",lesseqqgtr:"\u2a8b",LessEqualGreater:"\u22da",LessFullEqual:"\u2266",LessGreater:"\u2276",lessgtr:"\u2276",LessLess:"\u2aa1",lesssim:"\u2272",LessSlantEqual:"\u2a7d",LessTilde:"\u2272",lfisht:"\u297c",lfloor:"\u230a",Lfr:"\ud835\udd0f",lfr:"\ud835\udd29",lg:"\u2276",lgE:"\u2a91",lHar:"\u2962",lhard:"\u21bd",lharu:"\u21bc",lharul:"\u296a",lhblk:"\u2584",LJcy:"\u0409",ljcy:"\u0459",llarr:"\u21c7",ll:"\u226a",Ll:"\u22d8",llcorner:"\u231e",Lleftarrow:"\u21da",llhard:"\u296b",lltri:"\u25fa",Lmidot:"\u013f",lmidot:"\u0140",lmoustache:"\u23b0",lmoust:"\u23b0",lnap:"\u2a89",lnapprox:"\u2a89",lne:"\u2a87",lnE:"\u2268",lneq:"\u2a87",lneqq:"\u2268",lnsim:"\u22e6",loang:"\u27ec",loarr:"\u21fd",lobrk:"\u27e6",longleftarrow:"\u27f5",LongLeftArrow:"\u27f5",Longleftarrow:"\u27f8",longleftrightarrow:"\u27f7",LongLeftRightArrow:"\u27f7",Longleftrightarrow:"\u27fa",longmapsto:"\u27fc",longrightarrow:"\u27f6",LongRightArrow:"\u27f6",Longrightarrow:"\u27f9",looparrowleft:"\u21ab",looparrowright:"\u21ac",lopar:"\u2985",Lopf:"\ud835\udd43",lopf:"\ud835\udd5d",loplus:"\u2a2d",lotimes:"\u2a34",lowast:"\u2217",lowbar:"_",LowerLeftArrow:"\u2199",LowerRightArrow:"\u2198",loz:"\u25ca",lozenge:"\u25ca",lozf:"\u29eb",lpar:"(",lparlt:"\u2993",lrarr:"\u21c6",lrcorner:"\u231f",lrhar:"\u21cb",lrhard:"\u296d",lrm:"\u200e",lrtri:"\u22bf",lsaquo:"\u2039",lscr:"\ud835\udcc1",Lscr:"\u2112",lsh:"\u21b0",Lsh:"\u21b0",lsim:"\u2272",lsime:"\u2a8d",lsimg:"\u2a8f",lsqb:"[",lsquo:"\u2018",lsquor:"\u201a",Lstrok:"\u0141",lstrok:"\u0142",ltcc:"\u2aa6",ltcir:"\u2a79",lt:"<",LT:"<",Lt:"\u226a",ltdot:"\u22d6",lthree:"\u22cb",ltimes:"\u22c9",ltlarr:"\u2976",ltquest:"\u2a7b",ltri:"\u25c3",ltrie:"\u22b4",ltrif:"\u25c2",ltrPar:"\u2996",lurdshar:"\u294a",luruhar:"\u2966",lvertneqq:"\u2268\ufe00",lvnE:"\u2268\ufe00",macr:"\xaf",male:"\u2642",malt:"\u2720",maltese:"\u2720",Map:"\u2905",map:"\u21a6",mapsto:"\u21a6",mapstodown:"\u21a7",mapstoleft:"\u21a4",mapstoup:"\u21a5",marker:"\u25ae",mcomma:"\u2a29",Mcy:"\u041c",mcy:"\u043c",mdash:"\u2014",mDDot:"\u223a",measuredangle:"\u2221",MediumSpace:"\u205f",Mellintrf:"\u2133",Mfr:"\ud835\udd10",mfr:"\ud835\udd2a",mho:"\u2127",micro:"\xb5",midast:"*",midcir:"\u2af0",mid:"\u2223",middot:"\xb7",minusb:"\u229f",minus:"\u2212",minusd:"\u2238",minusdu:"\u2a2a",MinusPlus:"\u2213",mlcp:"\u2adb",mldr:"\u2026",mnplus:"\u2213",models:"\u22a7",Mopf:"\ud835\udd44",mopf:"\ud835\udd5e",mp:"\u2213",mscr:"\ud835\udcc2",Mscr:"\u2133",mstpos:"\u223e",Mu:"\u039c",mu:"\u03bc",multimap:"\u22b8",mumap:"\u22b8",nabla:"\u2207",Nacute:"\u0143",nacute:"\u0144",nang:"\u2220\u20d2",nap:"\u2249",napE:"\u2a70\u0338",napid:"\u224b\u0338",napos:"\u0149",napprox:"\u2249",natural:"\u266e",naturals:"\u2115",natur:"\u266e",nbsp:"\xa0",nbump:"\u224e\u0338",nbumpe:"\u224f\u0338",ncap:"\u2a43",Ncaron:"\u0147",ncaron:"\u0148",Ncedil:"\u0145",ncedil:"\u0146",ncong:"\u2247",ncongdot:"\u2a6d\u0338",ncup:"\u2a42",Ncy:"\u041d",ncy:"\u043d",ndash:"\u2013",nearhk:"\u2924",nearr:"\u2197",neArr:"\u21d7",nearrow:"\u2197",ne:"\u2260",nedot:"\u2250\u0338",NegativeMediumSpace:"\u200b",NegativeThickSpace:"\u200b",NegativeThinSpace:"\u200b",NegativeVeryThinSpace:"\u200b",nequiv:"\u2262",nesear:"\u2928",nesim:"\u2242\u0338",NestedGreaterGreater:"\u226b",NestedLessLess:"\u226a",NewLine:"\n",nexist:"\u2204",nexists:"\u2204",Nfr:"\ud835\udd11",nfr:"\ud835\udd2b",ngE:"\u2267\u0338",nge:"\u2271",ngeq:"\u2271",ngeqq:"\u2267\u0338",ngeqslant:"\u2a7e\u0338",nges:"\u2a7e\u0338",nGg:"\u22d9\u0338",ngsim:"\u2275",nGt:"\u226b\u20d2",ngt:"\u226f",ngtr:"\u226f",nGtv:"\u226b\u0338",nharr:"\u21ae",nhArr:"\u21ce",nhpar:"\u2af2",ni:"\u220b",nis:"\u22fc",nisd:"\u22fa",niv:"\u220b",NJcy:"\u040a",njcy:"\u045a",nlarr:"\u219a",nlArr:"\u21cd",nldr:"\u2025",nlE:"\u2266\u0338",nle:"\u2270",nleftarrow:"\u219a",nLeftarrow:"\u21cd",nleftrightarrow:"\u21ae",nLeftrightarrow:"\u21ce",nleq:"\u2270",nleqq:"\u2266\u0338",nleqslant:"\u2a7d\u0338",nles:"\u2a7d\u0338",nless:"\u226e",nLl:"\u22d8\u0338",nlsim:"\u2274",nLt:"\u226a\u20d2",nlt:"\u226e",nltri:"\u22ea",nltrie:"\u22ec",nLtv:"\u226a\u0338",nmid:"\u2224",NoBreak:"\u2060",NonBreakingSpace:"\xa0",nopf:"\ud835\udd5f",Nopf:"\u2115",Not:"\u2aec",not:"\xac",NotCongruent:"\u2262",NotCupCap:"\u226d",NotDoubleVerticalBar:"\u2226",NotElement:"\u2209",NotEqual:"\u2260",NotEqualTilde:"\u2242\u0338",NotExists:"\u2204",NotGreater:"\u226f",NotGreaterEqual:"\u2271",NotGreaterFullEqual:"\u2267\u0338",NotGreaterGreater:"\u226b\u0338",NotGreaterLess:"\u2279",NotGreaterSlantEqual:"\u2a7e\u0338",NotGreaterTilde:"\u2275",NotHumpDownHump:"\u224e\u0338",NotHumpEqual:"\u224f\u0338",notin:"\u2209",notindot:"\u22f5\u0338",notinE:"\u22f9\u0338",notinva:"\u2209",notinvb:"\u22f7",notinvc:"\u22f6",NotLeftTriangleBar:"\u29cf\u0338",NotLeftTriangle:"\u22ea",NotLeftTriangleEqual:"\u22ec",NotLess:"\u226e",NotLessEqual:"\u2270",NotLessGreater:"\u2278",NotLessLess:"\u226a\u0338",NotLessSlantEqual:"\u2a7d\u0338",NotLessTilde:"\u2274",NotNestedGreaterGreater:"\u2aa2\u0338",NotNestedLessLess:"\u2aa1\u0338",notni:"\u220c",notniva:"\u220c",notnivb:"\u22fe",notnivc:"\u22fd",NotPrecedes:"\u2280",NotPrecedesEqual:"\u2aaf\u0338",NotPrecedesSlantEqual:"\u22e0",NotReverseElement:"\u220c",NotRightTriangleBar:"\u29d0\u0338",NotRightTriangle:"\u22eb",NotRightTriangleEqual:"\u22ed",NotSquareSubset:"\u228f\u0338",NotSquareSubsetEqual:"\u22e2",NotSquareSuperset:"\u2290\u0338",NotSquareSupersetEqual:"\u22e3",NotSubset:"\u2282\u20d2",NotSubsetEqual:"\u2288",NotSucceeds:"\u2281",NotSucceedsEqual:"\u2ab0\u0338",NotSucceedsSlantEqual:"\u22e1",NotSucceedsTilde:"\u227f\u0338",NotSuperset:"\u2283\u20d2",NotSupersetEqual:"\u2289",NotTilde:"\u2241",NotTildeEqual:"\u2244",NotTildeFullEqual:"\u2247",NotTildeTilde:"\u2249",NotVerticalBar:"\u2224",nparallel:"\u2226",npar:"\u2226",nparsl:"\u2afd\u20e5",npart:"\u2202\u0338",npolint:"\u2a14",npr:"\u2280",nprcue:"\u22e0",nprec:"\u2280",npreceq:"\u2aaf\u0338",npre:"\u2aaf\u0338",nrarrc:"\u2933\u0338",nrarr:"\u219b",nrArr:"\u21cf",nrarrw:"\u219d\u0338",nrightarrow:"\u219b",nRightarrow:"\u21cf",nrtri:"\u22eb",nrtrie:"\u22ed",nsc:"\u2281",nsccue:"\u22e1",nsce:"\u2ab0\u0338",Nscr:"\ud835\udca9",nscr:"\ud835\udcc3",nshortmid:"\u2224",nshortparallel:"\u2226",nsim:"\u2241",nsime:"\u2244",nsimeq:"\u2244",nsmid:"\u2224",nspar:"\u2226",nsqsube:"\u22e2",nsqsupe:"\u22e3",nsub:"\u2284",nsubE:"\u2ac5\u0338",nsube:"\u2288",nsubset:"\u2282\u20d2",nsubseteq:"\u2288",nsubseteqq:"\u2ac5\u0338",nsucc:"\u2281",nsucceq:"\u2ab0\u0338",nsup:"\u2285",nsupE:"\u2ac6\u0338",nsupe:"\u2289",nsupset:"\u2283\u20d2",nsupseteq:"\u2289",nsupseteqq:"\u2ac6\u0338",ntgl:"\u2279",Ntilde:"\xd1",ntilde:"\xf1",ntlg:"\u2278",ntriangleleft:"\u22ea",ntrianglelefteq:"\u22ec",ntriangleright:"\u22eb",ntrianglerighteq:"\u22ed",Nu:"\u039d",nu:"\u03bd",num:"#",numero:"\u2116",numsp:"\u2007",nvap:"\u224d\u20d2",nvdash:"\u22ac",nvDash:"\u22ad",nVdash:"\u22ae",nVDash:"\u22af",nvge:"\u2265\u20d2",nvgt:">\u20d2",nvHarr:"\u2904",nvinfin:"\u29de",nvlArr:"\u2902",nvle:"\u2264\u20d2",nvlt:"<\u20d2",nvltrie:"\u22b4\u20d2",nvrArr:"\u2903",nvrtrie:"\u22b5\u20d2",nvsim:"\u223c\u20d2",nwarhk:"\u2923",nwarr:"\u2196",nwArr:"\u21d6",nwarrow:"\u2196",nwnear:"\u2927",Oacute:"\xd3",oacute:"\xf3",oast:"\u229b",Ocirc:"\xd4",ocirc:"\xf4",ocir:"\u229a",Ocy:"\u041e",ocy:"\u043e",odash:"\u229d",Odblac:"\u0150",odblac:"\u0151",odiv:"\u2a38",odot:"\u2299",odsold:"\u29bc",OElig:"\u0152",oelig:"\u0153",ofcir:"\u29bf",Ofr:"\ud835\udd12",ofr:"\ud835\udd2c",ogon:"\u02db",Ograve:"\xd2",ograve:"\xf2",ogt:"\u29c1",ohbar:"\u29b5",ohm:"\u03a9",oint:"\u222e",olarr:"\u21ba",olcir:"\u29be",olcross:"\u29bb",oline:"\u203e",olt:"\u29c0",Omacr:"\u014c",omacr:"\u014d",Omega:"\u03a9",omega:"\u03c9",Omicron:"\u039f",omicron:"\u03bf",omid:"\u29b6",ominus:"\u2296",Oopf:"\ud835\udd46",oopf:"\ud835\udd60",opar:"\u29b7",OpenCurlyDoubleQuote:"\u201c",OpenCurlyQuote:"\u2018",operp:"\u29b9",oplus:"\u2295",orarr:"\u21bb",Or:"\u2a54",or:"\u2228",ord:"\u2a5d",order:"\u2134",orderof:"\u2134",ordf:"\xaa",ordm:"\xba",origof:"\u22b6",oror:"\u2a56",orslope:"\u2a57",orv:"\u2a5b",oS:"\u24c8",Oscr:"\ud835\udcaa",oscr:"\u2134",Oslash:"\xd8",oslash:"\xf8",osol:"\u2298",Otilde:"\xd5",otilde:"\xf5",otimesas:"\u2a36",Otimes:"\u2a37",otimes:"\u2297",Ouml:"\xd6",ouml:"\xf6",ovbar:"\u233d",OverBar:"\u203e",OverBrace:"\u23de",OverBracket:"\u23b4",OverParenthesis:"\u23dc",para:"\xb6",parallel:"\u2225",par:"\u2225",parsim:"\u2af3",parsl:"\u2afd",part:"\u2202",PartialD:"\u2202",Pcy:"\u041f",pcy:"\u043f",percnt:"%",period:".",permil:"\u2030",perp:"\u22a5",pertenk:"\u2031",Pfr:"\ud835\udd13",pfr:"\ud835\udd2d",Phi:"\u03a6",phi:"\u03c6",phiv:"\u03d5",phmmat:"\u2133",phone:"\u260e",Pi:"\u03a0",pi:"\u03c0",pitchfork:"\u22d4",piv:"\u03d6",planck:"\u210f",planckh:"\u210e",plankv:"\u210f",plusacir:"\u2a23",plusb:"\u229e",pluscir:"\u2a22",plus:"+",plusdo:"\u2214",plusdu:"\u2a25",pluse:"\u2a72",PlusMinus:"\xb1",plusmn:"\xb1",plussim:"\u2a26",plustwo:"\u2a27",pm:"\xb1",Poincareplane:"\u210c",pointint:"\u2a15",popf:"\ud835\udd61",Popf:"\u2119",pound:"\xa3",prap:"\u2ab7",Pr:"\u2abb",pr:"\u227a",prcue:"\u227c",precapprox:"\u2ab7",prec:"\u227a",preccurlyeq:"\u227c",Precedes:"\u227a",PrecedesEqual:"\u2aaf",PrecedesSlantEqual:"\u227c",PrecedesTilde:"\u227e",preceq:"\u2aaf",precnapprox:"\u2ab9",precneqq:"\u2ab5",precnsim:"\u22e8",pre:"\u2aaf",prE:"\u2ab3",precsim:"\u227e",prime:"\u2032",Prime:"\u2033",primes:"\u2119",prnap:"\u2ab9",prnE:"\u2ab5",prnsim:"\u22e8",prod:"\u220f",Product:"\u220f",profalar:"\u232e",profline:"\u2312",profsurf:"\u2313",prop:"\u221d",Proportional:"\u221d",Proportion:"\u2237",propto:"\u221d",prsim:"\u227e",prurel:"\u22b0",Pscr:"\ud835\udcab",pscr:"\ud835\udcc5",Psi:"\u03a8",psi:"\u03c8",puncsp:"\u2008",Qfr:"\ud835\udd14",qfr:"\ud835\udd2e",qint:"\u2a0c",qopf:"\ud835\udd62",Qopf:"\u211a",qprime:"\u2057",Qscr:"\ud835\udcac",qscr:"\ud835\udcc6",quaternions:"\u210d",quatint:"\u2a16",quest:"?",questeq:"\u225f",quot:'"',QUOT:'"',rAarr:"\u21db",race:"\u223d\u0331",Racute:"\u0154",racute:"\u0155",radic:"\u221a",raemptyv:"\u29b3",rang:"\u27e9",Rang:"\u27eb",rangd:"\u2992",range:"\u29a5",rangle:"\u27e9",raquo:"\xbb",rarrap:"\u2975",rarrb:"\u21e5",rarrbfs:"\u2920",rarrc:"\u2933",rarr:"\u2192",Rarr:"\u21a0",rArr:"\u21d2",rarrfs:"\u291e",rarrhk:"\u21aa",rarrlp:"\u21ac",rarrpl:"\u2945",rarrsim:"\u2974",Rarrtl:"\u2916",rarrtl:"\u21a3",rarrw:"\u219d",ratail:"\u291a",rAtail:"\u291c",ratio:"\u2236",rationals:"\u211a",rbarr:"\u290d",rBarr:"\u290f",RBarr:"\u2910",rbbrk:"\u2773",rbrace:"}",rbrack:"]",rbrke:"\u298c",rbrksld:"\u298e",rbrkslu:"\u2990",Rcaron:"\u0158",rcaron:"\u0159",Rcedil:"\u0156",rcedil:"\u0157",rceil:"\u2309",rcub:"}",Rcy:"\u0420",rcy:"\u0440",rdca:"\u2937",rdldhar:"\u2969",rdquo:"\u201d",rdquor:"\u201d",rdsh:"\u21b3",real:"\u211c",realine:"\u211b",realpart:"\u211c",reals:"\u211d",Re:"\u211c",rect:"\u25ad",reg:"\xae",REG:"\xae",ReverseElement:"\u220b",ReverseEquilibrium:"\u21cb",ReverseUpEquilibrium:"\u296f",rfisht:"\u297d",rfloor:"\u230b",rfr:"\ud835\udd2f",Rfr:"\u211c",rHar:"\u2964",rhard:"\u21c1",rharu:"\u21c0",rharul:"\u296c",Rho:"\u03a1",rho:"\u03c1",rhov:"\u03f1",RightAngleBracket:"\u27e9",RightArrowBar:"\u21e5",rightarrow:"\u2192",RightArrow:"\u2192",Rightarrow:"\u21d2",RightArrowLeftArrow:"\u21c4",rightarrowtail:"\u21a3",RightCeiling:"\u2309",RightDoubleBracket:"\u27e7",RightDownTeeVector:"\u295d",RightDownVectorBar:"\u2955",RightDownVector:"\u21c2",RightFloor:"\u230b",rightharpoondown:"\u21c1",rightharpoonup:"\u21c0",rightleftarrows:"\u21c4",rightleftharpoons:"\u21cc",rightrightarrows:"\u21c9",rightsquigarrow:"\u219d",RightTeeArrow:"\u21a6",RightTee:"\u22a2",RightTeeVector:"\u295b",rightthreetimes:"\u22cc",RightTriangleBar:"\u29d0",RightTriangle:"\u22b3",RightTriangleEqual:"\u22b5",RightUpDownVector:"\u294f",RightUpTeeVector:"\u295c",RightUpVectorBar:"\u2954",RightUpVector:"\u21be",RightVectorBar:"\u2953",RightVector:"\u21c0",ring:"\u02da",risingdotseq:"\u2253",rlarr:"\u21c4",rlhar:"\u21cc",rlm:"\u200f",rmoustache:"\u23b1",rmoust:"\u23b1",rnmid:"\u2aee",roang:"\u27ed",roarr:"\u21fe",robrk:"\u27e7",ropar:"\u2986",ropf:"\ud835\udd63",Ropf:"\u211d",roplus:"\u2a2e",rotimes:"\u2a35",RoundImplies:"\u2970",rpar:")",rpargt:"\u2994",rppolint:"\u2a12",rrarr:"\u21c9",Rrightarrow:"\u21db",rsaquo:"\u203a",rscr:"\ud835\udcc7",Rscr:"\u211b",rsh:"\u21b1",Rsh:"\u21b1",rsqb:"]",rsquo:"\u2019",rsquor:"\u2019",rthree:"\u22cc",rtimes:"\u22ca",rtri:"\u25b9",rtrie:"\u22b5",rtrif:"\u25b8",rtriltri:"\u29ce",RuleDelayed:"\u29f4",ruluhar:"\u2968",rx:"\u211e",Sacute:"\u015a",sacute:"\u015b",sbquo:"\u201a",scap:"\u2ab8",Scaron:"\u0160",scaron:"\u0161",Sc:"\u2abc",sc:"\u227b",sccue:"\u227d",sce:"\u2ab0",scE:"\u2ab4",Scedil:"\u015e",scedil:"\u015f",Scirc:"\u015c",scirc:"\u015d",scnap:"\u2aba",scnE:"\u2ab6",scnsim:"\u22e9",scpolint:"\u2a13",scsim:"\u227f",Scy:"\u0421",scy:"\u0441",sdotb:"\u22a1",sdot:"\u22c5",sdote:"\u2a66",searhk:"\u2925",searr:"\u2198",seArr:"\u21d8",searrow:"\u2198",sect:"\xa7",semi:";",seswar:"\u2929",setminus:"\u2216",setmn:"\u2216",sext:"\u2736",Sfr:"\ud835\udd16",sfr:"\ud835\udd30",sfrown:"\u2322",sharp:"\u266f",SHCHcy:"\u0429",shchcy:"\u0449",SHcy:"\u0428",shcy:"\u0448",ShortDownArrow:"\u2193",ShortLeftArrow:"\u2190",shortmid:"\u2223",shortparallel:"\u2225",ShortRightArrow:"\u2192",ShortUpArrow:"\u2191",shy:"\xad",Sigma:"\u03a3",sigma:"\u03c3",sigmaf:"\u03c2",sigmav:"\u03c2",sim:"\u223c",simdot:"\u2a6a",sime:"\u2243",simeq:"\u2243",simg:"\u2a9e",simgE:"\u2aa0",siml:"\u2a9d",simlE:"\u2a9f",simne:"\u2246",simplus:"\u2a24",simrarr:"\u2972",slarr:"\u2190",SmallCircle:"\u2218",smallsetminus:"\u2216",smashp:"\u2a33",smeparsl:"\u29e4",smid:"\u2223",smile:"\u2323",smt:"\u2aaa",smte:"\u2aac",smtes:"\u2aac\ufe00",SOFTcy:"\u042c",softcy:"\u044c",solbar:"\u233f",solb:"\u29c4",sol:"/",Sopf:"\ud835\udd4a",sopf:"\ud835\udd64",spades:"\u2660",spadesuit:"\u2660",spar:"\u2225",sqcap:"\u2293",sqcaps:"\u2293\ufe00",sqcup:"\u2294",sqcups:"\u2294\ufe00",Sqrt:"\u221a",sqsub:"\u228f",sqsube:"\u2291",sqsubset:"\u228f",sqsubseteq:"\u2291",sqsup:"\u2290",sqsupe:"\u2292",sqsupset:"\u2290",sqsupseteq:"\u2292",square:"\u25a1",Square:"\u25a1",SquareIntersection:"\u2293",SquareSubset:"\u228f",SquareSubsetEqual:"\u2291",SquareSuperset:"\u2290",SquareSupersetEqual:"\u2292",SquareUnion:"\u2294",squarf:"\u25aa",squ:"\u25a1",squf:"\u25aa",srarr:"\u2192",Sscr:"\ud835\udcae",sscr:"\ud835\udcc8",ssetmn:"\u2216",ssmile:"\u2323",sstarf:"\u22c6",Star:"\u22c6",star:"\u2606",starf:"\u2605",straightepsilon:"\u03f5",straightphi:"\u03d5",strns:"\xaf",sub:"\u2282",Sub:"\u22d0",subdot:"\u2abd",subE:"\u2ac5",sube:"\u2286",subedot:"\u2ac3",submult:"\u2ac1",subnE:"\u2acb",subne:"\u228a",subplus:"\u2abf",subrarr:"\u2979",subset:"\u2282",Subset:"\u22d0",subseteq:"\u2286",subseteqq:"\u2ac5",SubsetEqual:"\u2286",subsetneq:"\u228a",subsetneqq:"\u2acb",subsim:"\u2ac7",subsub:"\u2ad5",subsup:"\u2ad3",succapprox:"\u2ab8",succ:"\u227b",succcurlyeq:"\u227d",Succeeds:"\u227b",SucceedsEqual:"\u2ab0",SucceedsSlantEqual:"\u227d",SucceedsTilde:"\u227f",succeq:"\u2ab0",succnapprox:"\u2aba",succneqq:"\u2ab6",succnsim:"\u22e9",succsim:"\u227f",SuchThat:"\u220b",sum:"\u2211",Sum:"\u2211",sung:"\u266a",sup1:"\xb9",sup2:"\xb2",sup3:"\xb3",sup:"\u2283",Sup:"\u22d1",supdot:"\u2abe",supdsub:"\u2ad8",supE:"\u2ac6",supe:"\u2287",supedot:"\u2ac4",Superset:"\u2283",SupersetEqual:"\u2287",suphsol:"\u27c9",suphsub:"\u2ad7",suplarr:"\u297b",supmult:"\u2ac2",supnE:"\u2acc",supne:"\u228b",supplus:"\u2ac0",supset:"\u2283",Supset:"\u22d1",supseteq:"\u2287",supseteqq:"\u2ac6",supsetneq:"\u228b",supsetneqq:"\u2acc",supsim:"\u2ac8",supsub:"\u2ad4",supsup:"\u2ad6",swarhk:"\u2926",swarr:"\u2199",swArr:"\u21d9",swarrow:"\u2199",swnwar:"\u292a",szlig:"\xdf",Tab:"\t",target:"\u2316",Tau:"\u03a4",tau:"\u03c4",tbrk:"\u23b4",Tcaron:"\u0164",tcaron:"\u0165",Tcedil:"\u0162",tcedil:"\u0163",Tcy:"\u0422",tcy:"\u0442",tdot:"\u20db",telrec:"\u2315",Tfr:"\ud835\udd17",tfr:"\ud835\udd31",there4:"\u2234",therefore:"\u2234",Therefore:"\u2234",Theta:"\u0398",theta:"\u03b8",thetasym:"\u03d1",thetav:"\u03d1",thickapprox:"\u2248",thicksim:"\u223c",ThickSpace:"\u205f\u200a",ThinSpace:"\u2009",thinsp:"\u2009",thkap:"\u2248",thksim:"\u223c",THORN:"\xde",thorn:"\xfe",tilde:"\u02dc",Tilde:"\u223c",TildeEqual:"\u2243",TildeFullEqual:"\u2245",TildeTilde:"\u2248",timesbar:"\u2a31",timesb:"\u22a0",times:"\xd7",timesd:"\u2a30",tint:"\u222d",toea:"\u2928",topbot:"\u2336",topcir:"\u2af1",top:"\u22a4",Topf:"\ud835\udd4b",topf:"\ud835\udd65",topfork:"\u2ada",tosa:"\u2929",tprime:"\u2034",trade:"\u2122",TRADE:"\u2122",triangle:"\u25b5",triangledown:"\u25bf",triangleleft:"\u25c3",trianglelefteq:"\u22b4",triangleq:"\u225c",triangleright:"\u25b9",trianglerighteq:"\u22b5",tridot:"\u25ec",trie:"\u225c",triminus:"\u2a3a",TripleDot:"\u20db",triplus:"\u2a39",trisb:"\u29cd",tritime:"\u2a3b",trpezium:"\u23e2",Tscr:"\ud835\udcaf",tscr:"\ud835\udcc9",TScy:"\u0426",tscy:"\u0446",TSHcy:"\u040b",tshcy:"\u045b",Tstrok:"\u0166",tstrok:"\u0167",twixt:"\u226c",twoheadleftarrow:"\u219e",twoheadrightarrow:"\u21a0",Uacute:"\xda",uacute:"\xfa",uarr:"\u2191",Uarr:"\u219f",uArr:"\u21d1",Uarrocir:"\u2949",Ubrcy:"\u040e",ubrcy:"\u045e",Ubreve:"\u016c",ubreve:"\u016d",Ucirc:"\xdb",ucirc:"\xfb",Ucy:"\u0423",ucy:"\u0443",udarr:"\u21c5",Udblac:"\u0170",udblac:"\u0171",udhar:"\u296e",ufisht:"\u297e",Ufr:"\ud835\udd18",ufr:"\ud835\udd32",Ugrave:"\xd9",ugrave:"\xf9",uHar:"\u2963",uharl:"\u21bf",uharr:"\u21be",uhblk:"\u2580",ulcorn:"\u231c",ulcorner:"\u231c",ulcrop:"\u230f",ultri:"\u25f8",Umacr:"\u016a",umacr:"\u016b",uml:"\xa8",UnderBar:"_",UnderBrace:"\u23df",UnderBracket:"\u23b5",UnderParenthesis:"\u23dd",Union:"\u22c3",UnionPlus:"\u228e",Uogon:"\u0172",uogon:"\u0173",Uopf:"\ud835\udd4c",uopf:"\ud835\udd66",UpArrowBar:"\u2912",uparrow:"\u2191",UpArrow:"\u2191",Uparrow:"\u21d1",UpArrowDownArrow:"\u21c5",updownarrow:"\u2195",UpDownArrow:"\u2195",Updownarrow:"\u21d5",UpEquilibrium:"\u296e",upharpoonleft:"\u21bf",upharpoonright:"\u21be",uplus:"\u228e",UpperLeftArrow:"\u2196",UpperRightArrow:"\u2197",upsi:"\u03c5",Upsi:"\u03d2",upsih:"\u03d2",Upsilon:"\u03a5",upsilon:"\u03c5",UpTeeArrow:"\u21a5",UpTee:"\u22a5",upuparrows:"\u21c8",urcorn:"\u231d",urcorner:"\u231d",urcrop:"\u230e",Uring:"\u016e",uring:"\u016f",urtri:"\u25f9",Uscr:"\ud835\udcb0",uscr:"\ud835\udcca",utdot:"\u22f0",Utilde:"\u0168",utilde:"\u0169",utri:"\u25b5",utrif:"\u25b4",uuarr:"\u21c8",Uuml:"\xdc",uuml:"\xfc",uwangle:"\u29a7",vangrt:"\u299c",varepsilon:"\u03f5",varkappa:"\u03f0",varnothing:"\u2205",varphi:"\u03d5",varpi:"\u03d6",varpropto:"\u221d",varr:"\u2195",vArr:"\u21d5",varrho:"\u03f1",varsigma:"\u03c2",varsubsetneq:"\u228a\ufe00",varsubsetneqq:"\u2acb\ufe00",varsupsetneq:"\u228b\ufe00",varsupsetneqq:"\u2acc\ufe00",vartheta:"\u03d1",vartriangleleft:"\u22b2",vartriangleright:"\u22b3",vBar:"\u2ae8",Vbar:"\u2aeb",vBarv:"\u2ae9",Vcy:"\u0412",vcy:"\u0432",vdash:"\u22a2",vDash:"\u22a8",Vdash:"\u22a9",VDash:"\u22ab",Vdashl:"\u2ae6",veebar:"\u22bb",vee:"\u2228",Vee:"\u22c1",veeeq:"\u225a",vellip:"\u22ee",verbar:"|",Verbar:"\u2016",vert:"|",Vert:"\u2016",VerticalBar:"\u2223",VerticalLine:"|",VerticalSeparator:"\u2758",VerticalTilde:"\u2240",VeryThinSpace:"\u200a",Vfr:"\ud835\udd19",vfr:"\ud835\udd33",vltri:"\u22b2",vnsub:"\u2282\u20d2",vnsup:"\u2283\u20d2",Vopf:"\ud835\udd4d",vopf:"\ud835\udd67",vprop:"\u221d",vrtri:"\u22b3",Vscr:"\ud835\udcb1",vscr:"\ud835\udccb",vsubnE:"\u2acb\ufe00",vsubne:"\u228a\ufe00",vsupnE:"\u2acc\ufe00",vsupne:"\u228b\ufe00",Vvdash:"\u22aa",vzigzag:"\u299a",Wcirc:"\u0174",wcirc:"\u0175",wedbar:"\u2a5f",wedge:"\u2227",Wedge:"\u22c0",wedgeq:"\u2259",weierp:"\u2118",Wfr:"\ud835\udd1a",wfr:"\ud835\udd34",Wopf:"\ud835\udd4e",wopf:"\ud835\udd68",wp:"\u2118",wr:"\u2240",wreath:"\u2240",Wscr:"\ud835\udcb2",wscr:"\ud835\udccc",xcap:"\u22c2",xcirc:"\u25ef",xcup:"\u22c3",xdtri:"\u25bd",Xfr:"\ud835\udd1b",xfr:"\ud835\udd35",xharr:"\u27f7",xhArr:"\u27fa",Xi:"\u039e",xi:"\u03be",xlarr:"\u27f5",xlArr:"\u27f8",xmap:"\u27fc",xnis:"\u22fb",xodot:"\u2a00",Xopf:"\ud835\udd4f",xopf:"\ud835\udd69",xoplus:"\u2a01",xotime:"\u2a02",xrarr:"\u27f6",xrArr:"\u27f9",Xscr:"\ud835\udcb3",xscr:"\ud835\udccd",xsqcup:"\u2a06",xuplus:"\u2a04",xutri:"\u25b3",xvee:"\u22c1",xwedge:"\u22c0",Yacute:"\xdd",yacute:"\xfd",YAcy:"\u042f",yacy:"\u044f",Ycirc:"\u0176",ycirc:"\u0177",Ycy:"\u042b",ycy:"\u044b",yen:"\xa5",Yfr:"\ud835\udd1c",yfr:"\ud835\udd36",YIcy:"\u0407",yicy:"\u0457",Yopf:"\ud835\udd50",yopf:"\ud835\udd6a",Yscr:"\ud835\udcb4",yscr:"\ud835\udcce",YUcy:"\u042e",yucy:"\u044e",yuml:"\xff",Yuml:"\u0178",Zacute:"\u0179",zacute:"\u017a",Zcaron:"\u017d",zcaron:"\u017e",Zcy:"\u0417",zcy:"\u0437",Zdot:"\u017b",zdot:"\u017c",zeetrf:"\u2128",ZeroWidthSpace:"\u200b",Zeta:"\u0396",zeta:"\u03b6",zfr:"\ud835\udd37",Zfr:"\u2128",ZHcy:"\u0416",zhcy:"\u0436",zigrarr:"\u21dd",zopf:"\ud835\udd6b",Zopf:"\u2124",Zscr:"\ud835\udcb5",zscr:"\ud835\udccf",zwj:"\u200d",zwnj:"\u200c"}},{}],53:[function(e,r,t){"use strict";function n(e){var r=Array.prototype.slice.call(arguments,1);return r.forEach(function(r){r&&Object.keys(r).forEach(function(t){e[t]=r[t]})}),e}function s(e){return Object.prototype.toString.call(e)}function o(e){return"[object String]"===s(e)}function i(e){return"[object Object]"===s(e)}function a(e){return"[object RegExp]"===s(e)}function c(e){return"[object Function]"===s(e)}function l(e){return e.replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function u(e){return Object.keys(e||{}).reduce(function(e,r){return e||k.hasOwnProperty(r)},!1)}function p(e){e.__index__=-1,e.__text_cache__=""}function h(e){return function(r,t){var n=r.slice(t);return e.test(n)?n.match(e)[0].length:0}}function f(){return function(e,r){r.normalize(e)}}function d(r){function t(e){return e.replace("%TLDS%",s.src_tlds)}function n(e,r){throw new Error('(LinkifyIt) Invalid schema "'+e+'": '+r)}var s=r.re=e("./lib/re")(r.__opts__),u=r.__tlds__.slice();r.onCompile(),r.__tlds_replaced__||u.push(v),u.push(s.src_xn),s.src_tlds=u.join("|"),s.email_fuzzy=RegExp(t(s.tpl_email_fuzzy),"i"),s.link_fuzzy=RegExp(t(s.tpl_link_fuzzy),"i"),s.link_no_ip_fuzzy=RegExp(t(s.tpl_link_no_ip_fuzzy),"i"),s.host_fuzzy_test=RegExp(t(s.tpl_host_fuzzy_test),"i");var d=[];r.__compiled__={},Object.keys(r.__schemas__).forEach(function(e){var t=r.__schemas__[e];if(null!==t){var s={validate:null,link:null};return r.__compiled__[e]=s,i(t)?(a(t.validate)?s.validate=h(t.validate):c(t.validate)?s.validate=t.validate:n(e,t),void(c(t.normalize)?s.normalize=t.normalize:t.normalize?n(e,t):s.normalize=f())):o(t)?void d.push(e):void n(e,t)}}),d.forEach(function(e){r.__compiled__[r.__schemas__[e]]&&(r.__compiled__[e].validate=r.__compiled__[r.__schemas__[e]].validate,r.__compiled__[e].normalize=r.__compiled__[r.__schemas__[e]].normalize)}),r.__compiled__[""]={validate:null,normalize:f()};var m=Object.keys(r.__compiled__).filter(function(e){return e.length>0&&r.__compiled__[e]}).map(l).join("|");r.re.schema_test=RegExp("(^|(?!_)(?:[><]|"+s.src_ZPCc+"))("+m+")","i"),r.re.schema_search=RegExp("(^|(?!_)(?:[><]|"+s.src_ZPCc+"))("+m+")","ig"),r.re.pretest=RegExp("("+r.re.schema_test.source+")|("+r.re.host_fuzzy_test.source+")|@","i"),p(r)}function m(e,r){var t=e.__index__,n=e.__last_index__,s=e.__text_cache__.slice(t,n);this.schema=e.__schema__.toLowerCase(),this.index=t+r,this.lastIndex=n+r,this.raw=s,this.text=s,this.url=s}function _(e,r){var t=new m(e,r);return e.__compiled__[t.schema].normalize(t,e),t}function g(e,r){return this instanceof g?(r||u(e)&&(r=e,e={}),this.__opts__=n({},k,r),this.__index__=-1,this.__last_index__=-1,this.__schema__="",this.__text_cache__="",this.__schemas__=n({},b,e),this.__compiled__={},this.__tlds__=y,this.__tlds_replaced__=!1,this.re={},void d(this)):new g(e,r)}var k={fuzzyLink:!0,fuzzyEmail:!0,fuzzyIP:!1},b={"http:":{validate:function(e,r,t){var n=e.slice(r);return t.re.http||(t.re.http=new RegExp("^\\/\\/"+t.re.src_auth+t.re.src_host_port_strict+t.re.src_path,"i")),t.re.http.test(n)?n.match(t.re.http)[0].length:0}},"https:":"http:","ftp:":"http:","//":{validate:function(e,r,t){var n=e.slice(r);return t.re.no_http||(t.re.no_http=new RegExp("^"+t.re.src_auth+"(?:localhost|(?:(?:"+t.re.src_domain+")\\.)+"+t.re.src_domain_root+")"+t.re.src_port+t.re.src_host_terminator+t.re.src_path,"i")),t.re.no_http.test(n)?r>=3&&":"===e[r-3]?0:r>=3&&"/"===e[r-3]?0:n.match(t.re.no_http)[0].length:0}},"mailto:":{validate:function(e,r,t){var n=e.slice(r);return t.re.mailto||(t.re.mailto=new RegExp("^"+t.re.src_email_name+"@"+t.re.src_host_strict,"i")),t.re.mailto.test(n)?n.match(t.re.mailto)[0].length:0}}},v="a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]",y="biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|\u0440\u0444".split("|");g.prototype.add=function(e,r){return this.__schemas__[e]=r,d(this),this},g.prototype.set=function(e){return this.__opts__=n(this.__opts__,e),this},g.prototype.test=function(e){if(this.__text_cache__=e,this.__index__=-1,!e.length)return!1;var r,t,n,s,o,i,a,c,l;if(this.re.schema_test.test(e))for(a=this.re.schema_search,a.lastIndex=0;null!==(r=a.exec(e));)if(s=this.testSchemaAt(e,r[2],a.lastIndex)){this.__schema__=r[2],this.__index__=r.index+r[1].length,this.__last_index__=r.index+r[0].length+s;break}return this.__opts__.fuzzyLink&&this.__compiled__["http:"]&&(c=e.search(this.re.host_fuzzy_test),c>=0&&(this.__index__<0||c<this.__index__)&&null!==(t=e.match(this.__opts__.fuzzyIP?this.re.link_fuzzy:this.re.link_no_ip_fuzzy))&&(o=t.index+t[1].length,(this.__index__<0||o<this.__index__)&&(this.__schema__="",this.__index__=o,this.__last_index__=t.index+t[0].length))),this.__opts__.fuzzyEmail&&this.__compiled__["mailto:"]&&(l=e.indexOf("@"),l>=0&&null!==(n=e.match(this.re.email_fuzzy))&&(o=n.index+n[1].length,i=n.index+n[0].length,(this.__index__<0||o<this.__index__||o===this.__index__&&i>this.__last_index__)&&(this.__schema__="mailto:",this.__index__=o,this.__last_index__=i))),this.__index__>=0},g.prototype.pretest=function(e){return this.re.pretest.test(e)},g.prototype.testSchemaAt=function(e,r,t){return this.__compiled__[r.toLowerCase()]?this.__compiled__[r.toLowerCase()].validate(e,t,this):0},g.prototype.match=function(e){var r=0,t=[];this.__index__>=0&&this.__text_cache__===e&&(t.push(_(this,r)),r=this.__last_index__);for(var n=r?e.slice(r):e;this.test(n);)t.push(_(this,r)),n=n.slice(this.__last_index__),r+=this.__last_index__;return t.length?t:null},g.prototype.tlds=function(e,r){return e=Array.isArray(e)?e:[e],r?(this.__tlds__=this.__tlds__.concat(e).sort().filter(function(e,r,t){return e!==t[r-1]}).reverse(),d(this),this):(this.__tlds__=e.slice(),this.__tlds_replaced__=!0,d(this),this)},g.prototype.normalize=function(e){e.schema||(e.url="http://"+e.url),"mailto:"!==e.schema||/^mailto:/i.test(e.url)||(e.url="mailto:"+e.url)},g.prototype.onCompile=function(){},r.exports=g},{"./lib/re":54}],54:[function(e,r,t){"use strict";r.exports=function(r){var t={};return t.src_Any=e("uc.micro/properties/Any/regex").source,t.src_Cc=e("uc.micro/categories/Cc/regex").source,t.src_Z=e("uc.micro/categories/Z/regex").source,t.src_P=e("uc.micro/categories/P/regex").source,t.src_ZPCc=[t.src_Z,t.src_P,t.src_Cc].join("|"),t.src_ZCc=[t.src_Z,t.src_Cc].join("|"),t.src_pseudo_letter="(?:(?!>|<|"+t.src_ZPCc+")"+t.src_Any+")",t.src_ip4="(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)",t.src_auth="(?:(?:(?!"+t.src_ZCc+"|[@/]).)+@)?",t.src_port="(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?",t.src_host_terminator="(?=$|>|<|"+t.src_ZPCc+")(?!-|_|:\\d|\\.-|\\.(?!$|"+t.src_ZPCc+"))",t.src_path="(?:[/?#](?:(?!"+t.src_ZCc+"|[()[\\]{}.,\"'?!\\-<>]).|\\[(?:(?!"+t.src_ZCc+"|\\]).)*\\]|\\((?:(?!"+t.src_ZCc+"|[)]).)*\\)|\\{(?:(?!"+t.src_ZCc+'|[}]).)*\\}|\\"(?:(?!'+t.src_ZCc+'|["]).)+\\"|\\\'(?:(?!'+t.src_ZCc+"|[']).)+\\'|\\'(?="+t.src_pseudo_letter+"|[-]).|\\.{2,3}[a-zA-Z0-9%/]|\\.(?!"+t.src_ZCc+"|[.]).|"+(r&&r["---"]?"\\-(?!--(?:[^-]|$))(?:-*)|":"\\-+|")+"\\,(?!"+t.src_ZCc+").|\\!(?!"+t.src_ZCc+"|[!]).|\\?(?!"+t.src_ZCc+"|[?]).)+|\\/)?",t.src_email_name='[\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]+',t.src_xn="xn--[a-z0-9\\-]{1,59}",t.src_domain_root="(?:"+t.src_xn+"|"+t.src_pseudo_letter+"{1,63})",t.src_domain="(?:"+t.src_xn+"|(?:"+t.src_pseudo_letter+")|(?:"+t.src_pseudo_letter+"(?:-(?!-)|"+t.src_pseudo_letter+"){0,61}"+t.src_pseudo_letter+"))",t.src_host="(?:(?:(?:(?:"+t.src_domain+")\\.)*"+t.src_domain_root+"))",t.tpl_host_fuzzy="(?:"+t.src_ip4+"|(?:(?:(?:"+t.src_domain+")\\.)+(?:%TLDS%)))",t.tpl_host_no_ip_fuzzy="(?:(?:(?:"+t.src_domain+")\\.)+(?:%TLDS%))",t.src_host_strict=t.src_host+t.src_host_terminator,t.tpl_host_fuzzy_strict=t.tpl_host_fuzzy+t.src_host_terminator,t.src_host_port_strict=t.src_host+t.src_port+t.src_host_terminator,t.tpl_host_port_fuzzy_strict=t.tpl_host_fuzzy+t.src_port+t.src_host_terminator,t.tpl_host_port_no_ip_fuzzy_strict=t.tpl_host_no_ip_fuzzy+t.src_port+t.src_host_terminator,t.tpl_host_fuzzy_test="localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:"+t.src_ZPCc+"|>|$))",t.tpl_email_fuzzy="(^|<|>|\\(|"+t.src_ZCc+")("+t.src_email_name+"@"+t.tpl_host_fuzzy_strict+")",t.tpl_link_fuzzy="(^|(?![.:/\\-_@])(?:[$+<=>^`|]|"+t.src_ZPCc+"))((?![$+<=>^`|])"+t.tpl_host_port_fuzzy_strict+t.src_path+")",t.tpl_link_no_ip_fuzzy="(^|(?![.:/\\-_@])(?:[$+<=>^`|]|"+t.src_ZPCc+"))((?![$+<=>^`|])"+t.tpl_host_port_no_ip_fuzzy_strict+t.src_path+")",t}},{"uc.micro/categories/Cc/regex":61,"uc.micro/categories/P/regex":63,"uc.micro/categories/Z/regex":64,"uc.micro/properties/Any/regex":66}],55:[function(e,r,t){"use strict";function n(e){var r,t,n=o[e];if(n)return n;for(n=o[e]=[],r=0;r<128;r++)t=String.fromCharCode(r),n.push(t);for(r=0;r<e.length;r++)t=e.charCodeAt(r),n[t]="%"+("0"+t.toString(16).toUpperCase()).slice(-2);return n}function s(e,r){var t;return"string"!=typeof r&&(r=s.defaultChars),t=n(r),e.replace(/(%[a-f0-9]{2})+/gi,function(e){var r,n,s,o,i,a,c,l="";for(r=0,n=e.length;r<n;r+=3)s=parseInt(e.slice(r+1,r+3),16),s<128?l+=t[s]:192===(224&s)&&r+3<n&&(o=parseInt(e.slice(r+4,r+6),16),128===(192&o))?(c=s<<6&1984|63&o,l+=c<128?"\ufffd\ufffd":String.fromCharCode(c),r+=3):224===(240&s)&&r+6<n&&(o=parseInt(e.slice(r+4,r+6),16),i=parseInt(e.slice(r+7,r+9),16),128===(192&o)&&128===(192&i))?(c=s<<12&61440|o<<6&4032|63&i,l+=c<2048||c>=55296&&c<=57343?"\ufffd\ufffd\ufffd":String.fromCharCode(c),r+=6):240===(248&s)&&r+9<n&&(o=parseInt(e.slice(r+4,r+6),16),i=parseInt(e.slice(r+7,r+9),16),a=parseInt(e.slice(r+10,r+12),16),128===(192&o)&&128===(192&i)&&128===(192&a))?(c=s<<18&1835008|o<<12&258048|i<<6&4032|63&a,c<65536||c>1114111?l+="\ufffd\ufffd\ufffd\ufffd":(c-=65536,l+=String.fromCharCode(55296+(c>>10),56320+(1023&c))),r+=9):l+="\ufffd";return l})}var o={};
s.defaultChars=";/?:@&=+$,#",s.componentChars="",r.exports=s},{}],56:[function(e,r,t){"use strict";function n(e){var r,t,n=o[e];if(n)return n;for(n=o[e]=[],r=0;r<128;r++)t=String.fromCharCode(r),/^[0-9a-z]$/i.test(t)?n.push(t):n.push("%"+("0"+r.toString(16).toUpperCase()).slice(-2));for(r=0;r<e.length;r++)n[e.charCodeAt(r)]=e[r];return n}function s(e,r,t){var o,i,a,c,l,u="";for("string"!=typeof r&&(t=r,r=s.defaultChars),"undefined"==typeof t&&(t=!0),l=n(r),o=0,i=e.length;o<i;o++)if(a=e.charCodeAt(o),t&&37===a&&o+2<i&&/^[0-9a-f]{2}$/i.test(e.slice(o+1,o+3)))u+=e.slice(o,o+3),o+=2;else if(a<128)u+=l[a];else if(a>=55296&&a<=57343){if(a>=55296&&a<=56319&&o+1<i&&(c=e.charCodeAt(o+1),c>=56320&&c<=57343)){u+=encodeURIComponent(e[o]+e[o+1]),o++;continue}u+="%EF%BF%BD"}else u+=encodeURIComponent(e[o]);return u}var o={};s.defaultChars=";/?:@&=+$,-_.!~*'()#",s.componentChars="-_.!~*'()",r.exports=s},{}],57:[function(e,r,t){"use strict";r.exports=function(e){var r="";return r+=e.protocol||"",r+=e.slashes?"//":"",r+=e.auth?e.auth+"@":"",r+=e.hostname&&e.hostname.indexOf(":")!==-1?"["+e.hostname+"]":e.hostname||"",r+=e.port?":"+e.port:"",r+=e.pathname||"",r+=e.search||"",r+=e.hash||""}},{}],58:[function(e,r,t){"use strict";r.exports.encode=e("./encode"),r.exports.decode=e("./decode"),r.exports.format=e("./format"),r.exports.parse=e("./parse")},{"./decode":55,"./encode":56,"./format":57,"./parse":59}],59:[function(e,r,t){"use strict";function n(){this.protocol=null,this.slashes=null,this.auth=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.pathname=null}function s(e,r){if(e&&e instanceof n)return e;var t=new n;return t.parse(e,r),t}var o=/^([a-z0-9.+-]+:)/i,i=/:[0-9]*$/,a=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,c=["<",">",'"',"`"," ","\r","\n","\t"],l=["{","}","|","\\","^","`"].concat(c),u=["'"].concat(l),p=["%","/","?",";","#"].concat(u),h=["/","?","#"],f=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,m=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,_={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0};n.prototype.parse=function(e,r){var t,n,s,i,c,l=e;if(l=l.trim(),!r&&1===e.split("#").length){var u=a.exec(l);if(u)return this.pathname=u[1],u[2]&&(this.search=u[2]),this}var k=o.exec(l);if(k&&(k=k[0],s=k.toLowerCase(),this.protocol=k,l=l.substr(k.length)),(r||k||l.match(/^\/\/[^@\/]+@[^@\/]+/))&&(c="//"===l.substr(0,2),!c||k&&_[k]||(l=l.substr(2),this.slashes=!0)),!_[k]&&(c||k&&!g[k])){var b=-1;for(t=0;t<h.length;t++)i=l.indexOf(h[t]),i!==-1&&(b===-1||i<b)&&(b=i);var v,y;for(y=b===-1?l.lastIndexOf("@"):l.lastIndexOf("@",b),y!==-1&&(v=l.slice(0,y),l=l.slice(y+1),this.auth=v),b=-1,t=0;t<p.length;t++)i=l.indexOf(p[t]),i!==-1&&(b===-1||i<b)&&(b=i);b===-1&&(b=l.length),":"===l[b-1]&&b--;var x=l.slice(0,b);l=l.slice(b),this.parseHost(x),this.hostname=this.hostname||"";var C="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!C){var A=this.hostname.split(/\./);for(t=0,n=A.length;t<n;t++){var w=A[t];if(w&&!w.match(d)){for(var D="",q=0,E=w.length;q<E;q++)D+=w.charCodeAt(q)>127?"x":w[q];if(!D.match(d)){var S=A.slice(0,t),F=A.slice(t+1),z=w.match(m);z&&(S.push(z[1]),F.unshift(z[2])),F.length&&(l=F.join(".")+l),this.hostname=S.join(".");break}}}}this.hostname.length>f&&(this.hostname=""),C&&(this.hostname=this.hostname.substr(1,this.hostname.length-2))}var L=l.indexOf("#");L!==-1&&(this.hash=l.substr(L),l=l.slice(0,L));var T=l.indexOf("?");return T!==-1&&(this.search=l.substr(T),l=l.slice(0,T)),l&&(this.pathname=l),g[s]&&this.hostname&&!this.pathname&&(this.pathname=""),this},n.prototype.parseHost=function(e){var r=i.exec(e);r&&(r=r[0],":"!==r&&(this.port=r.substr(1)),e=e.substr(0,e.length-r.length)),e&&(this.hostname=e)},r.exports=s},{}],60:[function(r,t,n){(function(r){!function(s){function o(e){throw new RangeError(R[e])}function i(e,r){for(var t=e.length,n=[];t--;)n[t]=r(e[t]);return n}function a(e,r){var t=e.split("@"),n="";t.length>1&&(n=t[0]+"@",e=t[1]),e=e.replace(T,".");var s=e.split("."),o=i(s,r).join(".");return n+o}function c(e){for(var r,t,n=[],s=0,o=e.length;s<o;)r=e.charCodeAt(s++),r>=55296&&r<=56319&&s<o?(t=e.charCodeAt(s++),56320==(64512&t)?n.push(((1023&r)<<10)+(1023&t)+65536):(n.push(r),s--)):n.push(r);return n}function l(e){return i(e,function(e){var r="";return e>65535&&(e-=65536,r+=B(e>>>10&1023|55296),e=56320|1023&e),r+=B(e)}).join("")}function u(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:C}function p(e,r){return e+22+75*(e<26)-((0!=r)<<5)}function h(e,r,t){var n=0;for(e=t?I(e/q):e>>1,e+=I(e/r);e>M*w>>1;n+=C)e=I(e/M);return I(n+(M+1)*e/(e+D))}function f(e){var r,t,n,s,i,a,c,p,f,d,m=[],_=e.length,g=0,k=S,b=E;for(t=e.lastIndexOf(F),t<0&&(t=0),n=0;n<t;++n)e.charCodeAt(n)>=128&&o("not-basic"),m.push(e.charCodeAt(n));for(s=t>0?t+1:0;s<_;){for(i=g,a=1,c=C;s>=_&&o("invalid-input"),p=u(e.charCodeAt(s++)),(p>=C||p>I((x-g)/a))&&o("overflow"),g+=p*a,f=c<=b?A:c>=b+w?w:c-b,!(p<f);c+=C)d=C-f,a>I(x/d)&&o("overflow"),a*=d;r=m.length+1,b=h(g-i,r,0==i),I(g/r)>x-k&&o("overflow"),k+=I(g/r),g%=r,m.splice(g++,0,k)}return l(m)}function d(e){var r,t,n,s,i,a,l,u,f,d,m,_,g,k,b,v=[];for(e=c(e),_=e.length,r=S,t=0,i=E,a=0;a<_;++a)m=e[a],m<128&&v.push(B(m));for(n=s=v.length,s&&v.push(F);n<_;){for(l=x,a=0;a<_;++a)m=e[a],m>=r&&m<l&&(l=m);for(g=n+1,l-r>I((x-t)/g)&&o("overflow"),t+=(l-r)*g,r=l,a=0;a<_;++a)if(m=e[a],m<r&&++t>x&&o("overflow"),m==r){for(u=t,f=C;d=f<=i?A:f>=i+w?w:f-i,!(u<d);f+=C)b=u-d,k=C-d,v.push(B(p(d+b%k,0))),u=I(b/k);v.push(B(p(u,0))),i=h(t,g,n==s),t=0,++n}++t,++r}return v.join("")}function m(e){return a(e,function(e){return z.test(e)?f(e.slice(4).toLowerCase()):e})}function _(e){return a(e,function(e){return L.test(e)?"xn--"+d(e):e})}var g="object"==typeof n&&n&&!n.nodeType&&n,k="object"==typeof t&&t&&!t.nodeType&&t,b="object"==typeof r&&r;b.global!==b&&b.window!==b&&b.self!==b||(s=b);var v,y,x=2147483647,C=36,A=1,w=26,D=38,q=700,E=72,S=128,F="-",z=/^xn--/,L=/[^\x20-\x7E]/,T=/[\x2E\u3002\uFF0E\uFF61]/g,R={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},M=C-A,I=Math.floor,B=String.fromCharCode;if(v={version:"1.4.1",ucs2:{decode:c,encode:l},decode:f,encode:d,toASCII:_,toUnicode:m},"function"==typeof e&&"object"==typeof e.amd&&e.amd)e("punycode",function(){return v});else if(g&&k)if(t.exports==g)k.exports=v;else for(y in v)v.hasOwnProperty(y)&&(g[y]=v[y]);else s.punycode=v}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],61:[function(e,r,t){r.exports=/[\0-\x1F\x7F-\x9F]/},{}],62:[function(e,r,t){r.exports=/[\xAD\u0600-\u0605\u061C\u06DD\u070F\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804\uDCBD|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/},{}],63:[function(e,r,t){r.exports=/[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E42\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDF3C-\uDF3E]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]/},{}],64:[function(e,r,t){r.exports=/[ \xA0\u1680\u2000-\u200A\u202F\u205F\u3000]/},{}],65:[function(e,r,t){r.exports.Any=e("./properties/Any/regex"),r.exports.Cc=e("./categories/Cc/regex"),r.exports.Cf=e("./categories/Cf/regex"),r.exports.P=e("./categories/P/regex"),r.exports.Z=e("./categories/Z/regex")},{"./categories/Cc/regex":61,"./categories/Cf/regex":62,"./categories/P/regex":63,"./categories/Z/regex":64,"./properties/Any/regex":66}],66:[function(e,r,t){r.exports=/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/},{}],67:[function(e,r,t){"use strict";r.exports=e("./lib/")},{"./lib/":9}]},{},[67])(67)});

/*global require*/
define('Core/KnockoutMarkdownBinding',[
    'markdown-it-sanitizer',
    'markdown-it'
], function (
    MarkdownItSanitizer,
    MarkdownIt) {
    'use strict';

    var htmlTagRegex = /<html(.|\s)*>(.|\s)*<\/html>/im;

    var md = new MarkdownIt({
        html: true,
        linkify: true
    });

    md.use(MarkdownItSanitizer, {
        imageClass: '',
        removeUnbalanced: false,
        removeUnknown: false
    });

    var KnockoutMarkdownBinding = {
        register: function (Knockout) {
            Knockout.bindingHandlers.markdown = {
                'init': function () {
                    // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
                    return { 'controlsDescendantBindings': true };
                },
                'update': function (element, valueAccessor) {
                    // Remove existing children of this element.
                    while (element.firstChild) {
                        Knockout.removeNode(element.firstChild);
                    }

                    var rawText = Knockout.unwrap(valueAccessor());

                    // If the text contains an <html> tag, don't try to interpret it as Markdown because
                    // we'll probably break it in the process.
                    var html;
                    if (htmlTagRegex.test(rawText)) {
                        html = rawText;
                    } else {
                        html = md.render(rawText);
                    }

                    var nodes = Knockout.utils.parseHtmlFragment(html, element);
                    element.className = element.className + ' markdown';

                    for (var i = 0; i < nodes.length; ++i) {
                        var node = nodes[i];
                        setAnchorTargets(node);
                        element.appendChild(node);
                    }
                }
            };
        }
    };

    function setAnchorTargets(element) {
        if (element instanceof HTMLAnchorElement) {
            element.target = '_blank';
        }

        if (element.childNodes && element.childNodes.length > 0) {
            for (var i = 0; i < element.childNodes.length; ++i) {
                setAnchorTargets(element.childNodes[i]);
            }
        }
    }

    return KnockoutMarkdownBinding;
});


/*! Hammer.JS - v2.0.7 - 2016-04-22
 * http://hammerjs.github.io/
 *
 * Copyright (c) 2016 Jorik Tangelder;
 * Licensed under the MIT license */
!function(a,b,c,d){"use strict";function e(a,b,c){return setTimeout(j(a,c),b)}function f(a,b,c){return Array.isArray(a)?(g(a,c[b],c),!0):!1}function g(a,b,c){var e;if(a)if(a.forEach)a.forEach(b,c);else if(a.length!==d)for(e=0;e<a.length;)b.call(c,a[e],e,a),e++;else for(e in a)a.hasOwnProperty(e)&&b.call(c,a[e],e,a)}function h(b,c,d){var e="DEPRECATED METHOD: "+c+"\n"+d+" AT \n";return function(){var c=new Error("get-stack-trace"),d=c&&c.stack?c.stack.replace(/^[^\(]+?[\n$]/gm,"").replace(/^\s+at\s+/gm,"").replace(/^Object.<anonymous>\s*\(/gm,"{anonymous}()@"):"Unknown Stack Trace",f=a.console&&(a.console.warn||a.console.log);return f&&f.call(a.console,e,d),b.apply(this,arguments)}}function i(a,b,c){var d,e=b.prototype;d=a.prototype=Object.create(e),d.constructor=a,d._super=e,c&&la(d,c)}function j(a,b){return function(){return a.apply(b,arguments)}}function k(a,b){return typeof a==oa?a.apply(b?b[0]||d:d,b):a}function l(a,b){return a===d?b:a}function m(a,b,c){g(q(b),function(b){a.addEventListener(b,c,!1)})}function n(a,b,c){g(q(b),function(b){a.removeEventListener(b,c,!1)})}function o(a,b){for(;a;){if(a==b)return!0;a=a.parentNode}return!1}function p(a,b){return a.indexOf(b)>-1}function q(a){return a.trim().split(/\s+/g)}function r(a,b,c){if(a.indexOf&&!c)return a.indexOf(b);for(var d=0;d<a.length;){if(c&&a[d][c]==b||!c&&a[d]===b)return d;d++}return-1}function s(a){return Array.prototype.slice.call(a,0)}function t(a,b,c){for(var d=[],e=[],f=0;f<a.length;){var g=b?a[f][b]:a[f];r(e,g)<0&&d.push(a[f]),e[f]=g,f++}return c&&(d=b?d.sort(function(a,c){return a[b]>c[b]}):d.sort()),d}function u(a,b){for(var c,e,f=b[0].toUpperCase()+b.slice(1),g=0;g<ma.length;){if(c=ma[g],e=c?c+f:b,e in a)return e;g++}return d}function v(){return ua++}function w(b){var c=b.ownerDocument||b;return c.defaultView||c.parentWindow||a}function x(a,b){var c=this;this.manager=a,this.callback=b,this.element=a.element,this.target=a.options.inputTarget,this.domHandler=function(b){k(a.options.enable,[a])&&c.handler(b)},this.init()}function y(a){var b,c=a.options.inputClass;return new(b=c?c:xa?M:ya?P:wa?R:L)(a,z)}function z(a,b,c){var d=c.pointers.length,e=c.changedPointers.length,f=b&Ea&&d-e===0,g=b&(Ga|Ha)&&d-e===0;c.isFirst=!!f,c.isFinal=!!g,f&&(a.session={}),c.eventType=b,A(a,c),a.emit("hammer.input",c),a.recognize(c),a.session.prevInput=c}function A(a,b){var c=a.session,d=b.pointers,e=d.length;c.firstInput||(c.firstInput=D(b)),e>1&&!c.firstMultiple?c.firstMultiple=D(b):1===e&&(c.firstMultiple=!1);var f=c.firstInput,g=c.firstMultiple,h=g?g.center:f.center,i=b.center=E(d);b.timeStamp=ra(),b.deltaTime=b.timeStamp-f.timeStamp,b.angle=I(h,i),b.distance=H(h,i),B(c,b),b.offsetDirection=G(b.deltaX,b.deltaY);var j=F(b.deltaTime,b.deltaX,b.deltaY);b.overallVelocityX=j.x,b.overallVelocityY=j.y,b.overallVelocity=qa(j.x)>qa(j.y)?j.x:j.y,b.scale=g?K(g.pointers,d):1,b.rotation=g?J(g.pointers,d):0,b.maxPointers=c.prevInput?b.pointers.length>c.prevInput.maxPointers?b.pointers.length:c.prevInput.maxPointers:b.pointers.length,C(c,b);var k=a.element;o(b.srcEvent.target,k)&&(k=b.srcEvent.target),b.target=k}function B(a,b){var c=b.center,d=a.offsetDelta||{},e=a.prevDelta||{},f=a.prevInput||{};b.eventType!==Ea&&f.eventType!==Ga||(e=a.prevDelta={x:f.deltaX||0,y:f.deltaY||0},d=a.offsetDelta={x:c.x,y:c.y}),b.deltaX=e.x+(c.x-d.x),b.deltaY=e.y+(c.y-d.y)}function C(a,b){var c,e,f,g,h=a.lastInterval||b,i=b.timeStamp-h.timeStamp;if(b.eventType!=Ha&&(i>Da||h.velocity===d)){var j=b.deltaX-h.deltaX,k=b.deltaY-h.deltaY,l=F(i,j,k);e=l.x,f=l.y,c=qa(l.x)>qa(l.y)?l.x:l.y,g=G(j,k),a.lastInterval=b}else c=h.velocity,e=h.velocityX,f=h.velocityY,g=h.direction;b.velocity=c,b.velocityX=e,b.velocityY=f,b.direction=g}function D(a){for(var b=[],c=0;c<a.pointers.length;)b[c]={clientX:pa(a.pointers[c].clientX),clientY:pa(a.pointers[c].clientY)},c++;return{timeStamp:ra(),pointers:b,center:E(b),deltaX:a.deltaX,deltaY:a.deltaY}}function E(a){var b=a.length;if(1===b)return{x:pa(a[0].clientX),y:pa(a[0].clientY)};for(var c=0,d=0,e=0;b>e;)c+=a[e].clientX,d+=a[e].clientY,e++;return{x:pa(c/b),y:pa(d/b)}}function F(a,b,c){return{x:b/a||0,y:c/a||0}}function G(a,b){return a===b?Ia:qa(a)>=qa(b)?0>a?Ja:Ka:0>b?La:Ma}function H(a,b,c){c||(c=Qa);var d=b[c[0]]-a[c[0]],e=b[c[1]]-a[c[1]];return Math.sqrt(d*d+e*e)}function I(a,b,c){c||(c=Qa);var d=b[c[0]]-a[c[0]],e=b[c[1]]-a[c[1]];return 180*Math.atan2(e,d)/Math.PI}function J(a,b){return I(b[1],b[0],Ra)+I(a[1],a[0],Ra)}function K(a,b){return H(b[0],b[1],Ra)/H(a[0],a[1],Ra)}function L(){this.evEl=Ta,this.evWin=Ua,this.pressed=!1,x.apply(this,arguments)}function M(){this.evEl=Xa,this.evWin=Ya,x.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}function N(){this.evTarget=$a,this.evWin=_a,this.started=!1,x.apply(this,arguments)}function O(a,b){var c=s(a.touches),d=s(a.changedTouches);return b&(Ga|Ha)&&(c=t(c.concat(d),"identifier",!0)),[c,d]}function P(){this.evTarget=bb,this.targetIds={},x.apply(this,arguments)}function Q(a,b){var c=s(a.touches),d=this.targetIds;if(b&(Ea|Fa)&&1===c.length)return d[c[0].identifier]=!0,[c,c];var e,f,g=s(a.changedTouches),h=[],i=this.target;if(f=c.filter(function(a){return o(a.target,i)}),b===Ea)for(e=0;e<f.length;)d[f[e].identifier]=!0,e++;for(e=0;e<g.length;)d[g[e].identifier]&&h.push(g[e]),b&(Ga|Ha)&&delete d[g[e].identifier],e++;return h.length?[t(f.concat(h),"identifier",!0),h]:void 0}function R(){x.apply(this,arguments);var a=j(this.handler,this);this.touch=new P(this.manager,a),this.mouse=new L(this.manager,a),this.primaryTouch=null,this.lastTouches=[]}function S(a,b){a&Ea?(this.primaryTouch=b.changedPointers[0].identifier,T.call(this,b)):a&(Ga|Ha)&&T.call(this,b)}function T(a){var b=a.changedPointers[0];if(b.identifier===this.primaryTouch){var c={x:b.clientX,y:b.clientY};this.lastTouches.push(c);var d=this.lastTouches,e=function(){var a=d.indexOf(c);a>-1&&d.splice(a,1)};setTimeout(e,cb)}}function U(a){for(var b=a.srcEvent.clientX,c=a.srcEvent.clientY,d=0;d<this.lastTouches.length;d++){var e=this.lastTouches[d],f=Math.abs(b-e.x),g=Math.abs(c-e.y);if(db>=f&&db>=g)return!0}return!1}function V(a,b){this.manager=a,this.set(b)}function W(a){if(p(a,jb))return jb;var b=p(a,kb),c=p(a,lb);return b&&c?jb:b||c?b?kb:lb:p(a,ib)?ib:hb}function X(){if(!fb)return!1;var b={},c=a.CSS&&a.CSS.supports;return["auto","manipulation","pan-y","pan-x","pan-x pan-y","none"].forEach(function(d){b[d]=c?a.CSS.supports("touch-action",d):!0}),b}function Y(a){this.options=la({},this.defaults,a||{}),this.id=v(),this.manager=null,this.options.enable=l(this.options.enable,!0),this.state=nb,this.simultaneous={},this.requireFail=[]}function Z(a){return a&sb?"cancel":a&qb?"end":a&pb?"move":a&ob?"start":""}function $(a){return a==Ma?"down":a==La?"up":a==Ja?"left":a==Ka?"right":""}function _(a,b){var c=b.manager;return c?c.get(a):a}function aa(){Y.apply(this,arguments)}function ba(){aa.apply(this,arguments),this.pX=null,this.pY=null}function ca(){aa.apply(this,arguments)}function da(){Y.apply(this,arguments),this._timer=null,this._input=null}function ea(){aa.apply(this,arguments)}function fa(){aa.apply(this,arguments)}function ga(){Y.apply(this,arguments),this.pTime=!1,this.pCenter=!1,this._timer=null,this._input=null,this.count=0}function ha(a,b){return b=b||{},b.recognizers=l(b.recognizers,ha.defaults.preset),new ia(a,b)}function ia(a,b){this.options=la({},ha.defaults,b||{}),this.options.inputTarget=this.options.inputTarget||a,this.handlers={},this.session={},this.recognizers=[],this.oldCssProps={},this.element=a,this.input=y(this),this.touchAction=new V(this,this.options.touchAction),ja(this,!0),g(this.options.recognizers,function(a){var b=this.add(new a[0](a[1]));a[2]&&b.recognizeWith(a[2]),a[3]&&b.requireFailure(a[3])},this)}function ja(a,b){var c=a.element;if(c.style){var d;g(a.options.cssProps,function(e,f){d=u(c.style,f),b?(a.oldCssProps[d]=c.style[d],c.style[d]=e):c.style[d]=a.oldCssProps[d]||""}),b||(a.oldCssProps={})}}function ka(a,c){var d=b.createEvent("Event");d.initEvent(a,!0,!0),d.gesture=c,c.target.dispatchEvent(d)}var la,ma=["","webkit","Moz","MS","ms","o"],na=b.createElement("div"),oa="function",pa=Math.round,qa=Math.abs,ra=Date.now;la="function"!=typeof Object.assign?function(a){if(a===d||null===a)throw new TypeError("Cannot convert undefined or null to object");for(var b=Object(a),c=1;c<arguments.length;c++){var e=arguments[c];if(e!==d&&null!==e)for(var f in e)e.hasOwnProperty(f)&&(b[f]=e[f])}return b}:Object.assign;var sa=h(function(a,b,c){for(var e=Object.keys(b),f=0;f<e.length;)(!c||c&&a[e[f]]===d)&&(a[e[f]]=b[e[f]]),f++;return a},"extend","Use `assign`."),ta=h(function(a,b){return sa(a,b,!0)},"merge","Use `assign`."),ua=1,va=/mobile|tablet|ip(ad|hone|od)|android/i,wa="ontouchstart"in a,xa=u(a,"PointerEvent")!==d,ya=wa&&va.test(navigator.userAgent),za="touch",Aa="pen",Ba="mouse",Ca="kinect",Da=25,Ea=1,Fa=2,Ga=4,Ha=8,Ia=1,Ja=2,Ka=4,La=8,Ma=16,Na=Ja|Ka,Oa=La|Ma,Pa=Na|Oa,Qa=["x","y"],Ra=["clientX","clientY"];x.prototype={handler:function(){},init:function(){this.evEl&&m(this.element,this.evEl,this.domHandler),this.evTarget&&m(this.target,this.evTarget,this.domHandler),this.evWin&&m(w(this.element),this.evWin,this.domHandler)},destroy:function(){this.evEl&&n(this.element,this.evEl,this.domHandler),this.evTarget&&n(this.target,this.evTarget,this.domHandler),this.evWin&&n(w(this.element),this.evWin,this.domHandler)}};var Sa={mousedown:Ea,mousemove:Fa,mouseup:Ga},Ta="mousedown",Ua="mousemove mouseup";i(L,x,{handler:function(a){var b=Sa[a.type];b&Ea&&0===a.button&&(this.pressed=!0),b&Fa&&1!==a.which&&(b=Ga),this.pressed&&(b&Ga&&(this.pressed=!1),this.callback(this.manager,b,{pointers:[a],changedPointers:[a],pointerType:Ba,srcEvent:a}))}});var Va={pointerdown:Ea,pointermove:Fa,pointerup:Ga,pointercancel:Ha,pointerout:Ha},Wa={2:za,3:Aa,4:Ba,5:Ca},Xa="pointerdown",Ya="pointermove pointerup pointercancel";a.MSPointerEvent&&!a.PointerEvent&&(Xa="MSPointerDown",Ya="MSPointerMove MSPointerUp MSPointerCancel"),i(M,x,{handler:function(a){var b=this.store,c=!1,d=a.type.toLowerCase().replace("ms",""),e=Va[d],f=Wa[a.pointerType]||a.pointerType,g=f==za,h=r(b,a.pointerId,"pointerId");e&Ea&&(0===a.button||g)?0>h&&(b.push(a),h=b.length-1):e&(Ga|Ha)&&(c=!0),0>h||(b[h]=a,this.callback(this.manager,e,{pointers:b,changedPointers:[a],pointerType:f,srcEvent:a}),c&&b.splice(h,1))}});var Za={touchstart:Ea,touchmove:Fa,touchend:Ga,touchcancel:Ha},$a="touchstart",_a="touchstart touchmove touchend touchcancel";i(N,x,{handler:function(a){var b=Za[a.type];if(b===Ea&&(this.started=!0),this.started){var c=O.call(this,a,b);b&(Ga|Ha)&&c[0].length-c[1].length===0&&(this.started=!1),this.callback(this.manager,b,{pointers:c[0],changedPointers:c[1],pointerType:za,srcEvent:a})}}});var ab={touchstart:Ea,touchmove:Fa,touchend:Ga,touchcancel:Ha},bb="touchstart touchmove touchend touchcancel";i(P,x,{handler:function(a){var b=ab[a.type],c=Q.call(this,a,b);c&&this.callback(this.manager,b,{pointers:c[0],changedPointers:c[1],pointerType:za,srcEvent:a})}});var cb=2500,db=25;i(R,x,{handler:function(a,b,c){var d=c.pointerType==za,e=c.pointerType==Ba;if(!(e&&c.sourceCapabilities&&c.sourceCapabilities.firesTouchEvents)){if(d)S.call(this,b,c);else if(e&&U.call(this,c))return;this.callback(a,b,c)}},destroy:function(){this.touch.destroy(),this.mouse.destroy()}});var eb=u(na.style,"touchAction"),fb=eb!==d,gb="compute",hb="auto",ib="manipulation",jb="none",kb="pan-x",lb="pan-y",mb=X();V.prototype={set:function(a){a==gb&&(a=this.compute()),fb&&this.manager.element.style&&mb[a]&&(this.manager.element.style[eb]=a),this.actions=a.toLowerCase().trim()},update:function(){this.set(this.manager.options.touchAction)},compute:function(){var a=[];return g(this.manager.recognizers,function(b){k(b.options.enable,[b])&&(a=a.concat(b.getTouchAction()))}),W(a.join(" "))},preventDefaults:function(a){var b=a.srcEvent,c=a.offsetDirection;if(this.manager.session.prevented)return void b.preventDefault();var d=this.actions,e=p(d,jb)&&!mb[jb],f=p(d,lb)&&!mb[lb],g=p(d,kb)&&!mb[kb];if(e){var h=1===a.pointers.length,i=a.distance<2,j=a.deltaTime<250;if(h&&i&&j)return}return g&&f?void 0:e||f&&c&Na||g&&c&Oa?this.preventSrc(b):void 0},preventSrc:function(a){this.manager.session.prevented=!0,a.preventDefault()}};var nb=1,ob=2,pb=4,qb=8,rb=qb,sb=16,tb=32;Y.prototype={defaults:{},set:function(a){return la(this.options,a),this.manager&&this.manager.touchAction.update(),this},recognizeWith:function(a){if(f(a,"recognizeWith",this))return this;var b=this.simultaneous;return a=_(a,this),b[a.id]||(b[a.id]=a,a.recognizeWith(this)),this},dropRecognizeWith:function(a){return f(a,"dropRecognizeWith",this)?this:(a=_(a,this),delete this.simultaneous[a.id],this)},requireFailure:function(a){if(f(a,"requireFailure",this))return this;var b=this.requireFail;return a=_(a,this),-1===r(b,a)&&(b.push(a),a.requireFailure(this)),this},dropRequireFailure:function(a){if(f(a,"dropRequireFailure",this))return this;a=_(a,this);var b=r(this.requireFail,a);return b>-1&&this.requireFail.splice(b,1),this},hasRequireFailures:function(){return this.requireFail.length>0},canRecognizeWith:function(a){return!!this.simultaneous[a.id]},emit:function(a){function b(b){c.manager.emit(b,a)}var c=this,d=this.state;qb>d&&b(c.options.event+Z(d)),b(c.options.event),a.additionalEvent&&b(a.additionalEvent),d>=qb&&b(c.options.event+Z(d))},tryEmit:function(a){return this.canEmit()?this.emit(a):void(this.state=tb)},canEmit:function(){for(var a=0;a<this.requireFail.length;){if(!(this.requireFail[a].state&(tb|nb)))return!1;a++}return!0},recognize:function(a){var b=la({},a);return k(this.options.enable,[this,b])?(this.state&(rb|sb|tb)&&(this.state=nb),this.state=this.process(b),void(this.state&(ob|pb|qb|sb)&&this.tryEmit(b))):(this.reset(),void(this.state=tb))},process:function(a){},getTouchAction:function(){},reset:function(){}},i(aa,Y,{defaults:{pointers:1},attrTest:function(a){var b=this.options.pointers;return 0===b||a.pointers.length===b},process:function(a){var b=this.state,c=a.eventType,d=b&(ob|pb),e=this.attrTest(a);return d&&(c&Ha||!e)?b|sb:d||e?c&Ga?b|qb:b&ob?b|pb:ob:tb}}),i(ba,aa,{defaults:{event:"pan",threshold:10,pointers:1,direction:Pa},getTouchAction:function(){var a=this.options.direction,b=[];return a&Na&&b.push(lb),a&Oa&&b.push(kb),b},directionTest:function(a){var b=this.options,c=!0,d=a.distance,e=a.direction,f=a.deltaX,g=a.deltaY;return e&b.direction||(b.direction&Na?(e=0===f?Ia:0>f?Ja:Ka,c=f!=this.pX,d=Math.abs(a.deltaX)):(e=0===g?Ia:0>g?La:Ma,c=g!=this.pY,d=Math.abs(a.deltaY))),a.direction=e,c&&d>b.threshold&&e&b.direction},attrTest:function(a){return aa.prototype.attrTest.call(this,a)&&(this.state&ob||!(this.state&ob)&&this.directionTest(a))},emit:function(a){this.pX=a.deltaX,this.pY=a.deltaY;var b=$(a.direction);b&&(a.additionalEvent=this.options.event+b),this._super.emit.call(this,a)}}),i(ca,aa,{defaults:{event:"pinch",threshold:0,pointers:2},getTouchAction:function(){return[jb]},attrTest:function(a){return this._super.attrTest.call(this,a)&&(Math.abs(a.scale-1)>this.options.threshold||this.state&ob)},emit:function(a){if(1!==a.scale){var b=a.scale<1?"in":"out";a.additionalEvent=this.options.event+b}this._super.emit.call(this,a)}}),i(da,Y,{defaults:{event:"press",pointers:1,time:251,threshold:9},getTouchAction:function(){return[hb]},process:function(a){var b=this.options,c=a.pointers.length===b.pointers,d=a.distance<b.threshold,f=a.deltaTime>b.time;if(this._input=a,!d||!c||a.eventType&(Ga|Ha)&&!f)this.reset();else if(a.eventType&Ea)this.reset(),this._timer=e(function(){this.state=rb,this.tryEmit()},b.time,this);else if(a.eventType&Ga)return rb;return tb},reset:function(){clearTimeout(this._timer)},emit:function(a){this.state===rb&&(a&&a.eventType&Ga?this.manager.emit(this.options.event+"up",a):(this._input.timeStamp=ra(),this.manager.emit(this.options.event,this._input)))}}),i(ea,aa,{defaults:{event:"rotate",threshold:0,pointers:2},getTouchAction:function(){return[jb]},attrTest:function(a){return this._super.attrTest.call(this,a)&&(Math.abs(a.rotation)>this.options.threshold||this.state&ob)}}),i(fa,aa,{defaults:{event:"swipe",threshold:10,velocity:.3,direction:Na|Oa,pointers:1},getTouchAction:function(){return ba.prototype.getTouchAction.call(this)},attrTest:function(a){var b,c=this.options.direction;return c&(Na|Oa)?b=a.overallVelocity:c&Na?b=a.overallVelocityX:c&Oa&&(b=a.overallVelocityY),this._super.attrTest.call(this,a)&&c&a.offsetDirection&&a.distance>this.options.threshold&&a.maxPointers==this.options.pointers&&qa(b)>this.options.velocity&&a.eventType&Ga},emit:function(a){var b=$(a.offsetDirection);b&&this.manager.emit(this.options.event+b,a),this.manager.emit(this.options.event,a)}}),i(ga,Y,{defaults:{event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:9,posThreshold:10},getTouchAction:function(){return[ib]},process:function(a){var b=this.options,c=a.pointers.length===b.pointers,d=a.distance<b.threshold,f=a.deltaTime<b.time;if(this.reset(),a.eventType&Ea&&0===this.count)return this.failTimeout();if(d&&f&&c){if(a.eventType!=Ga)return this.failTimeout();var g=this.pTime?a.timeStamp-this.pTime<b.interval:!0,h=!this.pCenter||H(this.pCenter,a.center)<b.posThreshold;this.pTime=a.timeStamp,this.pCenter=a.center,h&&g?this.count+=1:this.count=1,this._input=a;var i=this.count%b.taps;if(0===i)return this.hasRequireFailures()?(this._timer=e(function(){this.state=rb,this.tryEmit()},b.interval,this),ob):rb}return tb},failTimeout:function(){return this._timer=e(function(){this.state=tb},this.options.interval,this),tb},reset:function(){clearTimeout(this._timer)},emit:function(){this.state==rb&&(this._input.tapCount=this.count,this.manager.emit(this.options.event,this._input))}}),ha.VERSION="2.0.7",ha.defaults={domEvents:!1,touchAction:gb,enable:!0,inputTarget:null,inputClass:null,preset:[[ea,{enable:!1}],[ca,{enable:!1},["rotate"]],[fa,{direction:Na}],[ba,{direction:Na},["swipe"]],[ga],[ga,{event:"doubletap",taps:2},["tap"]],[da]],cssProps:{userSelect:"none",touchSelect:"none",touchCallout:"none",contentZooming:"none",userDrag:"none",tapHighlightColor:"rgba(0,0,0,0)"}};var ub=1,vb=2;ia.prototype={set:function(a){return la(this.options,a),a.touchAction&&this.touchAction.update(),a.inputTarget&&(this.input.destroy(),this.input.target=a.inputTarget,this.input.init()),this},stop:function(a){this.session.stopped=a?vb:ub},recognize:function(a){var b=this.session;if(!b.stopped){this.touchAction.preventDefaults(a);var c,d=this.recognizers,e=b.curRecognizer;(!e||e&&e.state&rb)&&(e=b.curRecognizer=null);for(var f=0;f<d.length;)c=d[f],b.stopped===vb||e&&c!=e&&!c.canRecognizeWith(e)?c.reset():c.recognize(a),!e&&c.state&(ob|pb|qb)&&(e=b.curRecognizer=c),f++}},get:function(a){if(a instanceof Y)return a;for(var b=this.recognizers,c=0;c<b.length;c++)if(b[c].options.event==a)return b[c];return null},add:function(a){if(f(a,"add",this))return this;var b=this.get(a.options.event);return b&&this.remove(b),this.recognizers.push(a),a.manager=this,this.touchAction.update(),a},remove:function(a){if(f(a,"remove",this))return this;if(a=this.get(a)){var b=this.recognizers,c=r(b,a);-1!==c&&(b.splice(c,1),this.touchAction.update())}return this},on:function(a,b){if(a!==d&&b!==d){var c=this.handlers;return g(q(a),function(a){c[a]=c[a]||[],c[a].push(b)}),this}},off:function(a,b){if(a!==d){var c=this.handlers;return g(q(a),function(a){b?c[a]&&c[a].splice(r(c[a],b),1):delete c[a]}),this}},emit:function(a,b){this.options.domEvents&&ka(a,b);var c=this.handlers[a]&&this.handlers[a].slice();if(c&&c.length){b.type=a,b.preventDefault=function(){b.srcEvent.preventDefault()};for(var d=0;d<c.length;)c[d](b),d++}},destroy:function(){this.element&&ja(this,!1),this.handlers={},this.session={},this.input.destroy(),this.element=null}},la(ha,{INPUT_START:Ea,INPUT_MOVE:Fa,INPUT_END:Ga,INPUT_CANCEL:Ha,STATE_POSSIBLE:nb,STATE_BEGAN:ob,STATE_CHANGED:pb,STATE_ENDED:qb,STATE_RECOGNIZED:rb,STATE_CANCELLED:sb,STATE_FAILED:tb,DIRECTION_NONE:Ia,DIRECTION_LEFT:Ja,DIRECTION_RIGHT:Ka,DIRECTION_UP:La,DIRECTION_DOWN:Ma,DIRECTION_HORIZONTAL:Na,DIRECTION_VERTICAL:Oa,DIRECTION_ALL:Pa,Manager:ia,Input:x,TouchAction:V,TouchInput:P,MouseInput:L,PointerEventInput:M,TouchMouseInput:R,SingleTouchInput:N,Recognizer:Y,AttrRecognizer:aa,Tap:ga,Pan:ba,Swipe:fa,Pinch:ca,Rotate:ea,Press:da,on:m,off:n,each:g,merge:ta,extend:sa,assign:la,inherit:i,bindFn:j,prefixed:u});var wb="undefined"!=typeof a?a:"undefined"!=typeof self?self:{};wb.Hammer=ha,"function"==typeof define&&define.amd?define('Hammer',[],function(){return ha}):"undefined"!=typeof module&&module.exports?module.exports=ha:a[c]=ha}(window,document,"Hammer");
//# sourceMappingURL=hammer.min.js.map;
/*global require*/
define('Core/KnockoutHammerBinding',[
    'KnockoutES5',
    'Hammer'
], function (Knockout, Hammer) {
    'use strict';

    var KnockoutHammerBinding = {
        register: function (Knockout) {
            Knockout.bindingHandlers.swipeLeft = {
                init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
                    var f = Knockout.unwrap(valueAccessor());
                    new Hammer(element).on('swipeleft', function (e) {
                        var viewModel = bindingContext.$data;
                        f.apply(viewModel, arguments);
                    });
                }
            };

            Knockout.bindingHandlers.swipeRight = {
                init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
                    var f = Knockout.unwrap(valueAccessor());
                    new Hammer(element).on('swiperight', function (e) {
                        var viewModel = bindingContext.$data;
                        f.apply(viewModel, arguments);
                    });
                }
            };
        }
    };

    return KnockoutHammerBinding;
});

/*global require*/
define('Core/registerKnockoutBindings',[
    'Cesium/Widgets/SvgPathBindingHandler',
    'KnockoutES5',
    'Core/KnockoutMarkdownBinding',
    'Core/KnockoutHammerBinding'
], function (
    SvgPathBindingHandler,
    Knockout,
    KnockoutMarkdownBinding,
    KnockoutHammerBinding) {
    'use strict';

    var registerKnockoutBindings = function () {
        SvgPathBindingHandler.register(Knockout);
        KnockoutMarkdownBinding.register(Knockout);
        KnockoutHammerBinding.register(Knockout);

        Knockout.bindingHandlers.embeddedComponent = {
            init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
                var component = Knockout.unwrap(valueAccessor());
                component.show(element);
                return { controlsDescendantBindings: true };
            },
            update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            }
        };
    };

    return registerKnockoutBindings;
});


/*global define*/
define('Core/createFragmentFromTemplate',[
], function () {
    'use strict';

    var createFragmentFromTemplate = function (htmlString) {
        var holder = document.createElement('div');
        holder.innerHTML = htmlString;

        var fragment = document.createDocumentFragment();
        while (holder.firstChild) {
            fragment.appendChild(holder.firstChild);
        }

        return fragment;
    };

    return createFragmentFromTemplate;
});


/*global require*/
define('Core/loadView',[
    'Cesium/Widgets/getElement',
    'KnockoutES5',
    'Core/createFragmentFromTemplate'
], function (
    getElement,
    Knockout,
    createFragmentFromTemplate) {
    'use strict';

    var loadView = function (htmlString, container, viewModel) {
        container = getElement(container);

        var fragment = createFragmentFromTemplate(htmlString);

        // Sadly, fragment.childNodes doesn't have a slice function.
        // This code could be replaced with Array.prototype.slice.call(fragment.childNodes)
        // but that seems slightly error prone.
        var nodes = [];

        var i;
        for (i = 0; i < fragment.childNodes.length; ++i) {
            nodes.push(fragment.childNodes[i]);
        }

        container.appendChild(fragment);

        for (i = 0; i < nodes.length; ++i) {
            var node = nodes[i];
            if (node.nodeType === 1 || node.nodeType === 8) {
                Knockout.applyBindings(viewModel, node);
            }
        }

        return nodes;
    };

    return loadView;
});
/*global define*/
define('ViewModels/DistanceLegendViewModel',[
    'Cesium/Core/defined',
    'Cesium/Core/DeveloperError',
    'Cesium/Core/EllipsoidGeodesic',
    'Cesium/Core/Cartesian2',
    'Cesium/Core/getTimestamp',
    'Cesium/Core/EventHelper',
    'KnockoutES5',
    'Core/loadView'
], function (
    defined,
    DeveloperError,
    EllipsoidGeodesic,
    Cartesian2,
    getTimestamp,
    EventHelper,
    Knockout,
    loadView) {
    'use strict';

    var DistanceLegendViewModel = function (options) {
        if (!defined(options) || !defined(options.terria)) {
            throw new DeveloperError('options.terria is required.');
        }

        this.terria = options.terria;
        this._removeSubscription = undefined;
        this._lastLegendUpdate = undefined;
        this.eventHelper = new EventHelper();

        this.distanceLabel = undefined;
        this.barWidth = undefined;

        this.enableDistanceLegend =  (defined(options.enableDistanceLegend))?options.enableDistanceLegend:true;

        Knockout.track(this, ['distanceLabel', 'barWidth']);

        this.eventHelper.add(this.terria.afterWidgetChanged, function () {
            if (defined(this._removeSubscription)) {
                this._removeSubscription();
                this._removeSubscription = undefined;
            }
        }, this);
//        this.terria.beforeWidgetChanged.addEventListener(function () {
//            if (defined(this._removeSubscription)) {
//                this._removeSubscription();
//                this._removeSubscription = undefined;
//            }
//        }, this);

        var that = this;

        function addUpdateSubscription() {
            if (defined(that.terria)) {
                var scene = that.terria.scene;
                that._removeSubscription = scene.postRender.addEventListener(function () {
                    updateDistanceLegendCesium(this, scene);
                }, that);
            }
        }

        addUpdateSubscription();
        this.eventHelper.add(this.terria.afterWidgetChanged, function () {
            addUpdateSubscription();
        }, this);
        //this.terria.afterWidgetChanged.addEventListener(function() {
        //    addUpdateSubscription();
        // }, this);
    };


    DistanceLegendViewModel.prototype.destroy = function () {

        this.eventHelper.removeAll();
    };

    DistanceLegendViewModel.prototype.show = function (container) {
        var testing ;
        if ( this.enableDistanceLegend)
        {
             testing = '<div class="distance-legend" data-bind="visible: distanceLabel && barWidth">' +
                '<div class="distance-legend-label" data-bind="text: distanceLabel"></div>' +
                '<div class="distance-legend-scale-bar" data-bind="style: { width: barWidth + \'px\', left: (5 + (125 - barWidth) / 2) + \'px\' }"></div>' +
                '</div>';
        }
        else
        {
             testing = '<div class="distance-legend"  style="display: none;" data-bind="visible: distanceLabel && barWidth">' +
                '<div class="distance-legend-label"  data-bind="text: distanceLabel"></div>' +
                '<div class="distance-legend-scale-bar"  data-bind="style: { width: barWidth + \'px\', left: (5 + (125 - barWidth) / 2) + \'px\' }"></div>' +
                '</div>';
        }
        loadView(testing, container, this);
        // loadView(distanceLegendTemplate, container, this);
        //loadView(require('fs').readFileSync(__dirname + '/../Views/DistanceLegend.html', 'utf8'), container, this);
    };

    DistanceLegendViewModel.create = function (options) {
        var result = new DistanceLegendViewModel(options);
        result.show(options.container);
        return result;
    };

    var geodesic = new EllipsoidGeodesic();

    var distances = [
        1, 2, 3, 5,
        10, 20, 30, 50,
        100, 200, 300, 500,
        1000, 2000, 3000, 5000,
        10000, 20000, 30000, 50000,
        100000, 200000, 300000, 500000,
        1000000, 2000000, 3000000, 5000000,
        10000000, 20000000, 30000000, 50000000];

    function updateDistanceLegendCesium(viewModel, scene) {
        if (!viewModel.enableDistanceLegend)
        {
             viewModel.barWidth = undefined;
            viewModel.distanceLabel = undefined;
            return;
        }
        var now = getTimestamp();
        if (now < viewModel._lastLegendUpdate + 250) {
            return;
        }

        viewModel._lastLegendUpdate = now;

        // Find the distance between two pixels at the bottom center of the screen.
        var width = scene.canvas.clientWidth;
        var height = scene.canvas.clientHeight;

        var left = scene.camera.getPickRay(new Cartesian2((width / 2) | 0, height - 1));
        var right = scene.camera.getPickRay(new Cartesian2(1 + (width / 2) | 0, height - 1));

        var globe = scene.globe;
        var leftPosition = globe.pick(left, scene);
        var rightPosition = globe.pick(right, scene);

        if (!defined(leftPosition) || !defined(rightPosition)) {
            viewModel.barWidth = undefined;
            viewModel.distanceLabel = undefined;
            return;
        }

        var leftCartographic = globe.ellipsoid.cartesianToCartographic(leftPosition);
        var rightCartographic = globe.ellipsoid.cartesianToCartographic(rightPosition);

        geodesic.setEndPoints(leftCartographic, rightCartographic);
        var pixelDistance = geodesic.surfaceDistance;

        // Find the first distance that makes the scale bar less than 100 pixels.
        var maxBarWidth = 100;
        var distance;
        for (var i = distances.length - 1; !defined(distance) && i >= 0; --i) {
            if (distances[i] / pixelDistance < maxBarWidth) {
                distance = distances[i];
            }
        }

        if (defined(distance)) {
            var label;
            if (distance >= 1000) {
                label = (distance / 1000).toString() + ' km';
            } else {
                label = distance.toString() + ' m';
            }

            viewModel.barWidth = (distance / pixelDistance) | 0;
            viewModel.distanceLabel = label;
        } else {
            viewModel.barWidth = undefined;
            viewModel.distanceLabel = undefined;
        }
    }



    return DistanceLegendViewModel;
});

/*global require*/
define('ViewModels/UserInterfaceControl',[
    'Cesium/Core/defined',
    'Cesium/Core/DeveloperError',
    'KnockoutES5'
], function (
    defined,
    DeveloperError,
    Knockout) {
    'use strict';

    /**
     * The view-model for a control in the user interface
     *
     * @alias UserInterfaceControl
     * @constructor
     * @abstract
     *
     * @param {Terria} terria The Terria instance.
     */
    var UserInterfaceControl = function (terria) {

        if (!defined(terria)) {
            throw new DeveloperError('terria is required');
        }

        this._terria = terria;

        /**
         * Gets or sets the name of the control which is set as the controls title.
         * This property is observable.
         * @type {String}
         */
        this.name = 'Unnamed Control';

        /**
         * Gets or sets the text to be displayed in the UI control.
         * This property is observable.
         * @type {String}
         */
        this.text = undefined;

        /**
         * Gets or sets the svg icon of the control.  This property is observable.
         * @type {Object}
         */
        this.svgIcon = undefined;

        /**
         * Gets or sets the height of the svg icon.  This property is observable.
         * @type {Integer}
         */
        this.svgHeight = undefined;

        /**
         * Gets or sets the width of the svg icon.  This property is observable.
         * @type {Integer}
         */
        this.svgWidth = undefined;

        /**
         * Gets or sets the CSS class of the control. This property is observable.
         * @type {String}
         */
        this.cssClass = undefined;

        /**
         * Gets or sets the property describing whether or not the control is in the active state.
         * This property is observable.
         * @type {Boolean}
         */
        this.isActive = false;

        Knockout.track(this, ['name', 'svgIcon', 'svgHeight', 'svgWidth', 'cssClass', 'isActive']);
    };

    Object.defineProperties(UserInterfaceControl.prototype, {
        /**
         * Gets the Terria instance.
         * @memberOf UserInterfaceControl.prototype
         * @type {Terria}
         */
        terria: {
            get: function () {
                return this._terria;
            }
        },
        /**
         * Gets a value indicating whether this button has text associated with it.
         * @type {Object}
         */
        hasText: {
            get: function () {
                return defined(this.text) && typeof this.text === 'string';
            }
        }

    });

    /**
     * When implemented in a derived class, performs an action when the user clicks
     * on this control.
     * @abstract
     * @protected
     */
    UserInterfaceControl.prototype.activate = function () {
        throw new DeveloperError('activate must be implemented in the derived class.');
    };

    return UserInterfaceControl;
});

/*global require*/
define('ViewModels/NavigationControl',[
    'ViewModels/UserInterfaceControl'
], function (
    UserInterfaceControl) {
    'use strict';

    /**
     * The view-model for a control in the navigation control tool bar
     *
     * @alias NavigationControl
     * @constructor
     * @abstract
     *
     * @param {Terria} terria The Terria instance.
     */
    var NavigationControl = function (terria) {
        UserInterfaceControl.apply(this, arguments);
    };

    NavigationControl.prototype = Object.create(UserInterfaceControl.prototype);

    return NavigationControl;
});

/*global define*/
define('SvgPaths/svgReset',[
], function () {
    'use strict';

    return 'M 7.5,0 C 3.375,0 0,3.375 0,7.5 0,11.625 3.375,15 7.5,15 c 3.46875,0 6.375,-2.4375 7.21875,-5.625 l -1.96875,0 C 12,11.53125 9.9375,13.125 7.5,13.125 4.40625,13.125 1.875,10.59375 1.875,7.5 1.875,4.40625 4.40625,1.875 7.5,1.875 c 1.59375,0 2.90625,0.65625 3.9375,1.6875 l -3,3 6.5625,0 L 15,0 12.75,2.25 C 11.4375,0.84375 9.5625,0 7.5,0 z';
});
/*global require*/
define('ViewModels/ResetViewNavigationControl',[
    'Cesium/Core/defined',
    'Cesium/Scene/Camera',
    'Cesium/Core/Rectangle',
    'Cesium/Core/Cartographic',
    'ViewModels/NavigationControl',
    'SvgPaths/svgReset'
], function (
        defined,
        Camera,
        Rectangle,
        Cartographic,
        NavigationControl,
        svgReset)
{
    'use strict';

    /**
     * The model for a zoom in control in the navigation control tool bar
     *
     * @alias ResetViewNavigationControl
     * @constructor
     * @abstract
     *
     * @param {Terria} terria The Terria instance.
     */
    var ResetViewNavigationControl = function (terria)
    {
        NavigationControl.apply(this, arguments);

        /**
         * Gets or sets the name of the control which is set as the control's title.
         * This property is observable.
         * @type {String}
         */
        this.name = 'Reset View';
        this.navigationLocked = false;

        /**
         * Gets or sets the svg icon of the control.  This property is observable.
         * @type {Object}
         */
        this.svgIcon = svgReset;

        /**
         * Gets or sets the height of the svg icon.  This property is observable.
         * @type {Integer}
         */
        this.svgHeight = 15;

        /**
         * Gets or sets the width of the svg icon.  This property is observable.
         * @type {Integer}
         */
        this.svgWidth = 15;

        /**
         * Gets or sets the CSS class of the control. This property is observable.
         * @type {String}
         */
        this.cssClass = "navigation-control-icon-reset";

    };

    ResetViewNavigationControl.prototype = Object.create(NavigationControl.prototype);
    
     ResetViewNavigationControl.prototype.setNavigationLocked = function (locked)
    {
        this.navigationLocked = locked;
    };

    ResetViewNavigationControl.prototype.resetView = function ()
    {
        //this.terria.analytics.logEvent('navigation', 'click', 'reset');
        if (this.navigationLocked)
        {
            return;
        }
        var scene = this.terria.scene;

        var sscc = scene.screenSpaceCameraController;
        if (!sscc.enableInputs)
        {
            return;
        }

        this.isActive = true;

        var camera = scene.camera;

        if (defined(this.terria.trackedEntity))
        {
            // when tracking do not reset to default view but to default view of tracked entity
            var trackedEntity = this.terria.trackedEntity;
            this.terria.trackedEntity = undefined;
            this.terria.trackedEntity = trackedEntity;
        }
        else
        {
            // reset to a default position or view defined in the options
            if (this.terria.options.defaultResetView)
            {
                if (this.terria.options.defaultResetView && this.terria.options.defaultResetView instanceof Cartographic)
                {
                    camera.flyTo({
                        destination: scene.globe.ellipsoid.cartographicToCartesian(this.terria.options.defaultResetView)
                    });
                }
                else if (this.terria.options.defaultResetView && this.terria.options.defaultResetView instanceof Rectangle)
                {
                    try
                    {
                        Rectangle.validate(this.terria.options.defaultResetView);
                        camera.flyTo({
                            destination: this.terria.options.defaultResetView
                        });
                    }
                    catch (e)
                    {
                        console.log("Cesium-navigation/ResetViewNavigationControl:   options.defaultResetView Cesium rectangle is  invalid!");
                    }
                }
            }
            else if (typeof camera.flyHome === "function")
            {
                camera.flyHome(1);
            }
            else
            {
                camera.flyTo({'destination': Camera.DEFAULT_VIEW_RECTANGLE, 'duration': 1});
            }
        }
        this.isActive = false;
    };

    /**
     * When implemented in a derived class, performs an action when the user clicks
     * on this control
     * @abstract
     * @protected
     */
    ResetViewNavigationControl.prototype.activate = function ()
    {
        this.resetView();
    };

    return ResetViewNavigationControl;
});

/*global require*/
define('Core/Utils',[
    'Cesium/Core/defined',
    'Cesium/Core/Ray',
    'Cesium/Core/Cartesian3',
    'Cesium/Core/Cartographic',
    'Cesium/Core/ReferenceFrame',
    'Cesium/Scene/SceneMode'
], function (
    defined,
    Ray,
    Cartesian3,
    Cartographic,
    ReferenceFrame,
    SceneMode) {
    'use strict';

    var Utils = {};

    var unprojectedScratch = new Cartographic();
    var rayScratch = new Ray();

    /**
     * gets the focus point of the camera
     * @param {Viewer|Widget} terria The terria
     * @param {boolean} inWorldCoordinates true to get the focus in world coordinates, otherwise get it in projection-specific map coordinates, in meters.
     * @param {Cartesian3} [result] The object in which the result will be stored.
     * @return {Cartesian3} The modified result parameter, a new instance if none was provided or undefined if there is no focus point.
     */
    Utils.getCameraFocus = function (terria, inWorldCoordinates, result) {
        var scene = terria.scene;
        var camera = scene.camera;

        if(scene.mode == SceneMode.MORPHING) {
            return undefined;
        }

        if(!defined(result)) {
            result = new Cartesian3();
        }

        // TODO bug when tracking: if entity moves the current position should be used and not only the one when starting orbiting/rotating
        // TODO bug when tracking: reset should reset to default view of tracked entity

        if(defined(terria.trackedEntity)) {
            result = terria.trackedEntity.position.getValue(terria.clock.currentTime, result);
        } else {
            rayScratch.origin = camera.positionWC;
            rayScratch.direction = camera.directionWC;
            result = scene.globe.pick(rayScratch, scene, result);
        }

        if (!defined(result)) {
            return undefined;
        }

        if(scene.mode == SceneMode.SCENE2D || scene.mode == SceneMode.COLUMBUS_VIEW) {
            result = camera.worldToCameraCoordinatesPoint(result, result);

            if(inWorldCoordinates) {
                result = scene.globe.ellipsoid.cartographicToCartesian(scene.mapProjection.unproject(result, unprojectedScratch), result);
            }
        } else {
            if(!inWorldCoordinates) {
                result = camera.worldToCameraCoordinatesPoint(result, result);
            }
        }

        return result;
    };

    return Utils;
});

/*global require*/
define('ViewModels/ZoomNavigationControl',[
    'Cesium/Core/defined',
    'Cesium/Core/Ray',
    'Cesium/Core/IntersectionTests',
    'Cesium/Core/Cartesian3',
    'Cesium/Scene/SceneMode',
    'ViewModels/NavigationControl',
    'Core/Utils'
], function (
    defined,
    Ray,
    IntersectionTests,
    Cartesian3,
    SceneMode,
    NavigationControl,
    Utils) {
    'use strict';

    /**
     * The model for a zoom in control in the navigation control tool bar
     *
     * @alias ZoomOutNavigationControl
     * @constructor
     * @abstract
     *
     * @param {Terria} terria The Terria instance.
     * @param {boolean} zoomIn is used for zooming in (true) or out (false)
     */
    var ZoomNavigationControl = function (terria, zoomIn) {
        NavigationControl.apply(this, arguments);

        /**
         * Gets or sets the name of the control which is set as the control's title.
         * This property is observable.
         * @type {String}
         */
        this.name = 'Zoom ' + (zoomIn ? 'In' : 'Out');

        /**
         * Gets or sets the text to be displayed in the nav control. Controls that
         * have text do not display the svgIcon.
         * This property is observable.
         * @type {String}
         */
        this.text = zoomIn ? '+' : '-';

        /**
         * Gets or sets the CSS class of the control. This property is observable.
         * @type {String}
         */
        this.cssClass = 'navigation-control-icon-zoom-' + (zoomIn ? 'in' : 'out');

        this.relativeAmount = 2;

        if (zoomIn) {
            // this ensures that zooming in is the inverse of zooming out and vice versa
            // e.g. the camera position remains when zooming in and out
            this.relativeAmount = 1 / this.relativeAmount;
        }
    };

    ZoomNavigationControl.prototype.relativeAmount = 1;

    ZoomNavigationControl.prototype = Object.create(NavigationControl.prototype);

    /**
     * When implemented in a derived class, performs an action when the user clicks
     * on this control
     * @abstract
     * @protected
     */
    ZoomNavigationControl.prototype.activate = function () {
        this.zoom(this.relativeAmount);
    };

    var cartesian3Scratch = new Cartesian3();

    ZoomNavigationControl.prototype.zoom = function (relativeAmount) {
        // this.terria.analytics.logEvent('navigation', 'click', 'zoomIn');

        this.isActive = true;

        if (defined(this.terria)) {
            var scene = this.terria.scene;

            var sscc = scene.screenSpaceCameraController;
            // do not zoom if it is disabled
            if (!sscc.enableInputs || !sscc.enableZoom) {
                return;
            }
            // TODO
//            if(scene.mode == SceneMode.COLUMBUS_VIEW && !sscc.enableTranslate) {
//                return;
//            }

            var camera = scene.camera;
            var orientation;

            switch (scene.mode) {
                case SceneMode.MORPHING:
                    break;
                case SceneMode.SCENE2D:
                    camera.zoomIn(camera.positionCartographic.height * (1 - this.relativeAmount));
                    break;
                default:
                    var focus;

                    if(defined(this.terria.trackedEntity)) {
                        focus = new Cartesian3();
                    } else {
                        focus = Utils.getCameraFocus(this.terria, false);
                    }

                    if (!defined(focus)) {
                        // Camera direction is not pointing at the globe, so use the ellipsoid horizon point as
                        // the focal point.
                        var ray = new Ray(camera.worldToCameraCoordinatesPoint(scene.globe.ellipsoid.cartographicToCartesian(camera.positionCartographic)), camera.directionWC);
                        focus = IntersectionTests.grazingAltitudeLocation(ray, scene.globe.ellipsoid);

                        orientation = {
                            heading: camera.heading,
                            pitch: camera.pitch,
                            roll: camera.roll
                        };
                    } else {
                        orientation = {
                            direction: camera.direction,
                            up: camera.up
                        };
                    }

                    var direction = Cartesian3.subtract(camera.position, focus, cartesian3Scratch);
                    var movementVector = Cartesian3.multiplyByScalar(direction, relativeAmount, direction);
                    var endPosition = Cartesian3.add(focus, movementVector, focus);

                    if (defined(this.terria.trackedEntity) || scene.mode == SceneMode.COLUMBUS_VIEW) {
                        // sometimes flyTo does not work (jumps to wrong position) so just set the position without any animation
                        // do not use flyTo when tracking an entity because during animatiuon the position of the entity may change
                        camera.position = endPosition;
                    } else {
                        camera.flyTo({
                            destination: endPosition,
                            orientation: orientation,
                            duration: 0.5,
                            convert: false
                        });
                    }
            }
        }

        // this.terria.notifyRepaintRequired();
        this.isActive = false;
    };

    return ZoomNavigationControl;
});

/*global define*/
define('SvgPaths/svgCompassOuterRing',[
], function () {
    'use strict';

    return 'm 66.5625,0 0,15.15625 3.71875,0 0,-10.40625 5.5,10.40625 4.375,0 0,-15.15625 -3.71875,0 0,10.40625 L 70.9375,0 66.5625,0 z M 72.5,20.21875 c -28.867432,0 -52.28125,23.407738 -52.28125,52.28125 0,28.87351 23.413818,52.3125 52.28125,52.3125 28.86743,0 52.28125,-23.43899 52.28125,-52.3125 0,-28.873512 -23.41382,-52.28125 -52.28125,-52.28125 z m 0,1.75 c 13.842515,0 26.368948,5.558092 35.5,14.5625 l -11.03125,11 0.625,0.625 11.03125,-11 c 8.9199,9.108762 14.4375,21.579143 14.4375,35.34375 0,13.764606 -5.5176,26.22729 -14.4375,35.34375 l -11.03125,-11 -0.625,0.625 11.03125,11 c -9.130866,9.01087 -21.658601,14.59375 -35.5,14.59375 -13.801622,0 -26.321058,-5.53481 -35.4375,-14.5 l 11.125,-11.09375 c 6.277989,6.12179 14.857796,9.90625 24.3125,9.90625 19.241896,0 34.875,-15.629154 34.875,-34.875 0,-19.245847 -15.633104,-34.84375 -34.875,-34.84375 -9.454704,0 -18.034511,3.760884 -24.3125,9.875 L 37.0625,36.4375 C 46.179178,27.478444 58.696991,21.96875 72.5,21.96875 z m -0.875,0.84375 0,13.9375 1.75,0 0,-13.9375 -1.75,0 z M 36.46875,37.0625 47.5625,48.15625 C 41.429794,54.436565 37.65625,63.027539 37.65625,72.5 c 0,9.472461 3.773544,18.055746 9.90625,24.34375 L 36.46875,107.9375 c -8.96721,-9.1247 -14.5,-21.624886 -14.5,-35.4375 0,-13.812615 5.53279,-26.320526 14.5,-35.4375 z M 72.5,39.40625 c 18.297686,0 33.125,14.791695 33.125,33.09375 0,18.302054 -14.827314,33.125 -33.125,33.125 -18.297687,0 -33.09375,-14.822946 -33.09375,-33.125 0,-18.302056 14.796063,-33.09375 33.09375,-33.09375 z M 22.84375,71.625 l 0,1.75 13.96875,0 0,-1.75 -13.96875,0 z m 85.5625,0 0,1.75 14,0 0,-1.75 -14,0 z M 71.75,108.25 l 0,13.9375 1.71875,0 0,-13.9375 -1.71875,0 z';
});
/*global define*/
define('SvgPaths/svgCompassGyro',[
], function () {
    'use strict';

    return 'm 72.71875,54.375 c -0.476702,0 -0.908208,0.245402 -1.21875,0.5625 -0.310542,0.317098 -0.551189,0.701933 -0.78125,1.1875 -0.172018,0.363062 -0.319101,0.791709 -0.46875,1.25 -6.91615,1.075544 -12.313231,6.656514 -13,13.625 -0.327516,0.117495 -0.661877,0.244642 -0.9375,0.375 -0.485434,0.22959 -0.901634,0.471239 -1.21875,0.78125 -0.317116,0.310011 -0.5625,0.742111 -0.5625,1.21875 l 0.03125,0 c 0,0.476639 0.245384,0.877489 0.5625,1.1875 0.317116,0.310011 0.702066,0.58291 1.1875,0.8125 0.35554,0.168155 0.771616,0.32165 1.21875,0.46875 1.370803,6.10004 6.420817,10.834127 12.71875,11.8125 0.146999,0.447079 0.30025,0.863113 0.46875,1.21875 0.230061,0.485567 0.470708,0.870402 0.78125,1.1875 0.310542,0.317098 0.742048,0.5625 1.21875,0.5625 0.476702,0 0.876958,-0.245402 1.1875,-0.5625 0.310542,-0.317098 0.582439,-0.701933 0.8125,-1.1875 0.172018,-0.363062 0.319101,-0.791709 0.46875,-1.25 6.249045,-1.017063 11.256351,-5.7184 12.625,-11.78125 0.447134,-0.1471 0.86321,-0.300595 1.21875,-0.46875 0.485434,-0.22959 0.901633,-0.502489 1.21875,-0.8125 0.317117,-0.310011 0.5625,-0.710861 0.5625,-1.1875 l -0.03125,0 c 0,-0.476639 -0.245383,-0.908739 -0.5625,-1.21875 C 89.901633,71.846239 89.516684,71.60459 89.03125,71.375 88.755626,71.244642 88.456123,71.117495 88.125,71 87.439949,64.078341 82.072807,58.503735 75.21875,57.375 c -0.15044,-0.461669 -0.326927,-0.884711 -0.5,-1.25 -0.230061,-0.485567 -0.501958,-0.870402 -0.8125,-1.1875 -0.310542,-0.317098 -0.710798,-0.5625 -1.1875,-0.5625 z m -0.0625,1.40625 c 0.03595,-0.01283 0.05968,0 0.0625,0 0.0056,0 0.04321,-0.02233 0.1875,0.125 0.144288,0.147334 0.34336,0.447188 0.53125,0.84375 0.06385,0.134761 0.123901,0.309578 0.1875,0.46875 -0.320353,-0.01957 -0.643524,-0.0625 -0.96875,-0.0625 -0.289073,0 -0.558569,0.04702 -0.84375,0.0625 C 71.8761,57.059578 71.936151,56.884761 72,56.75 c 0.18789,-0.396562 0.355712,-0.696416 0.5,-0.84375 0.07214,-0.07367 0.120304,-0.112167 0.15625,-0.125 z m 0,2.40625 c 0.448007,0 0.906196,0.05436 1.34375,0.09375 0.177011,0.592256 0.347655,1.271044 0.5,2.03125 0.475097,2.370753 0.807525,5.463852 0.9375,8.9375 -0.906869,-0.02852 -1.834463,-0.0625 -2.78125,-0.0625 -0.92298,0 -1.802327,0.03537 -2.6875,0.0625 0.138529,-3.473648 0.493653,-6.566747 0.96875,-8.9375 0.154684,-0.771878 0.320019,-1.463985 0.5,-2.0625 0.405568,-0.03377 0.804291,-0.0625 1.21875,-0.0625 z m -2.71875,0.28125 c -0.129732,0.498888 -0.259782,0.987558 -0.375,1.5625 -0.498513,2.487595 -0.838088,5.693299 -0.96875,9.25 -3.21363,0.15162 -6.119596,0.480068 -8.40625,0.9375 -0.682394,0.136509 -1.275579,0.279657 -1.84375,0.4375 0.799068,-6.135482 5.504716,-11.036454 11.59375,-12.1875 z M 75.5,58.5 c 6.043169,1.18408 10.705093,6.052712 11.5,12.15625 -0.569435,-0.155806 -1.200273,-0.302525 -1.875,-0.4375 -2.262525,-0.452605 -5.108535,-0.783809 -8.28125,-0.9375 -0.130662,-3.556701 -0.470237,-6.762405 -0.96875,-9.25 C 75.761959,59.467174 75.626981,58.990925 75.5,58.5 z m -2.84375,12.09375 c 0.959338,0 1.895843,0.03282 2.8125,0.0625 C 75.48165,71.267751 75.5,71.871028 75.5,72.5 c 0,1.228616 -0.01449,2.438313 -0.0625,3.59375 -0.897358,0.0284 -1.811972,0.0625 -2.75,0.0625 -0.927373,0 -1.831062,-0.03473 -2.71875,-0.0625 -0.05109,-1.155437 -0.0625,-2.365134 -0.0625,-3.59375 0,-0.628972 0.01741,-1.232249 0.03125,-1.84375 0.895269,-0.02827 1.783025,-0.0625 2.71875,-0.0625 z M 68.5625,70.6875 c -0.01243,0.60601 -0.03125,1.189946 -0.03125,1.8125 0,1.22431 0.01541,2.407837 0.0625,3.5625 -3.125243,-0.150329 -5.92077,-0.471558 -8.09375,-0.90625 -0.784983,-0.157031 -1.511491,-0.316471 -2.125,-0.5 -0.107878,-0.704096 -0.1875,-1.422089 -0.1875,-2.15625 0,-0.115714 0.02849,-0.228688 0.03125,-0.34375 0.643106,-0.20284 1.389577,-0.390377 2.25,-0.5625 2.166953,-0.433487 4.97905,-0.75541 8.09375,-0.90625 z m 8.3125,0.03125 c 3.075121,0.15271 5.824455,0.446046 7.96875,0.875 0.857478,0.171534 1.630962,0.360416 2.28125,0.5625 0.0027,0.114659 0,0.228443 0,0.34375 0,0.735827 -0.07914,1.450633 -0.1875,2.15625 -0.598568,0.180148 -1.29077,0.34562 -2.0625,0.5 -2.158064,0.431708 -4.932088,0.754666 -8.03125,0.90625 0.04709,-1.154663 0.0625,-2.33819 0.0625,-3.5625 0,-0.611824 -0.01924,-1.185379 -0.03125,-1.78125 z M 57.15625,72.5625 c 0.0023,0.572772 0.06082,1.131112 0.125,1.6875 -0.125327,-0.05123 -0.266577,-0.10497 -0.375,-0.15625 -0.396499,-0.187528 -0.665288,-0.387337 -0.8125,-0.53125 -0.147212,-0.143913 -0.15625,-0.182756 -0.15625,-0.1875 0,-0.0047 -0.02221,-0.07484 0.125,-0.21875 0.147212,-0.143913 0.447251,-0.312472 0.84375,-0.5 0.07123,-0.03369 0.171867,-0.06006 0.25,-0.09375 z m 31.03125,0 c 0.08201,0.03503 0.175941,0.05872 0.25,0.09375 0.396499,0.187528 0.665288,0.356087 0.8125,0.5 0.14725,0.14391 0.15625,0.21405 0.15625,0.21875 0,0.0047 -0.009,0.04359 -0.15625,0.1875 -0.147212,0.143913 -0.416001,0.343722 -0.8125,0.53125 -0.09755,0.04613 -0.233314,0.07889 -0.34375,0.125 0.06214,-0.546289 0.09144,-1.094215 0.09375,-1.65625 z m -29.5,3.625 c 0.479308,0.123125 0.983064,0.234089 1.53125,0.34375 2.301781,0.460458 5.229421,0.787224 8.46875,0.9375 0.167006,2.84339 0.46081,5.433176 0.875,7.5 0.115218,0.574942 0.245268,1.063612 0.375,1.5625 -5.463677,-1.028179 -9.833074,-5.091831 -11.25,-10.34375 z m 27.96875,0 C 85.247546,81.408945 80.919274,85.442932 75.5,86.5 c 0.126981,-0.490925 0.261959,-0.967174 0.375,-1.53125 0.41419,-2.066824 0.707994,-4.65661 0.875,-7.5 3.204493,-0.15162 6.088346,-0.480068 8.375,-0.9375 0.548186,-0.109661 1.051942,-0.220625 1.53125,-0.34375 z M 70.0625,77.53125 c 0.865391,0.02589 1.723666,0.03125 2.625,0.03125 0.912062,0 1.782843,-0.0048 2.65625,-0.03125 -0.165173,2.736408 -0.453252,5.207651 -0.84375,7.15625 -0.152345,0.760206 -0.322989,1.438994 -0.5,2.03125 -0.437447,0.03919 -0.895856,0.0625 -1.34375,0.0625 -0.414943,0 -0.812719,-0.02881 -1.21875,-0.0625 -0.177011,-0.592256 -0.347655,-1.271044 -0.5,-2.03125 -0.390498,-1.948599 -0.700644,-4.419842 -0.875,-7.15625 z m 1.75,10.28125 c 0.284911,0.01545 0.554954,0.03125 0.84375,0.03125 0.325029,0 0.648588,-0.01171 0.96875,-0.03125 -0.05999,0.148763 -0.127309,0.31046 -0.1875,0.4375 -0.18789,0.396562 -0.386962,0.696416 -0.53125,0.84375 -0.144288,0.147334 -0.181857,0.125 -0.1875,0.125 -0.0056,0 -0.07446,0.02233 -0.21875,-0.125 C 72.355712,88.946416 72.18789,88.646562 72,88.25 71.939809,88.12296 71.872486,87.961263 71.8125,87.8125 z';
});
/*global define*/
define('SvgPaths/svgCompassRotationMarker',[
], function () {
    'use strict';

    return 'M 72.46875,22.03125 C 59.505873,22.050338 46.521615,27.004287 36.6875,36.875 L 47.84375,47.96875 C 61.521556,34.240041 83.442603,34.227389 97.125,47.90625 l 11.125,-11.125 C 98.401629,26.935424 85.431627,22.012162 72.46875,22.03125 z';
});
/*global define*/
define('ViewModels/NavigationViewModel',[
    'Cesium/Core/defined',
    'Cesium/Core/Math',
    'Cesium/Core/getTimestamp',
    'Cesium/Core/EventHelper',
    'Cesium/Core/Transforms',
    'Cesium/Scene/SceneMode',
    'Cesium/Core/Cartesian2',
    'Cesium/Core/Cartesian3',
    'Cesium/Core/Matrix4',
    'Cesium/Core/BoundingSphere',
    'Cesium/Core/HeadingPitchRange',
    'KnockoutES5',
    'Core/loadView',
    'ViewModels/ResetViewNavigationControl',
    'ViewModels/ZoomNavigationControl',
    'SvgPaths/svgCompassOuterRing',
    'SvgPaths/svgCompassGyro',
    'SvgPaths/svgCompassRotationMarker',
    'Core/Utils'
], function (
        defined,
        CesiumMath,
        getTimestamp,
        EventHelper,
        Transforms,
        SceneMode,
        Cartesian2,
        Cartesian3,
        Matrix4,
        BoundingSphere,
        HeadingPitchRange,
        Knockout,
        loadView,
        ResetViewNavigationControl,
        ZoomNavigationControl,
        svgCompassOuterRing,
        svgCompassGyro,
        svgCompassRotationMarker,
        Utils)
{
    'use strict';

    var NavigationViewModel = function (options)
    {

        this.terria = options.terria;
        this.eventHelper = new EventHelper();
        this.enableZoomControls = (defined(options.enableZoomControls)) ? options.enableZoomControls : true;
        this.enableCompass = (defined(options.enableCompass)) ? options.enableCompass : true;
        this.navigationLocked = false;

        // if (this.showZoomControls)
        //   {
        this.controls = options.controls;
        if (!defined(this.controls))
        {
            this.controls = [
                new ZoomNavigationControl(this.terria, true),
                new ResetViewNavigationControl(this.terria),
                new ZoomNavigationControl(this.terria, false)
            ];
        }
        //}

        this.svgCompassOuterRing = svgCompassOuterRing;
        this.svgCompassGyro = svgCompassGyro;
        this.svgCompassRotationMarker = svgCompassRotationMarker;

        this.showCompass = defined(this.terria) && this.enableCompass;
        this.heading = this.showCompass ? this.terria.scene.camera.heading : 0.0;

        this.isOrbiting = false;
        this.orbitCursorAngle = 0;
        this.orbitCursorOpacity = 0.0;
        this.orbitLastTimestamp = 0;
        this.orbitFrame = undefined;
        this.orbitIsLook = false;
        this.orbitMouseMoveFunction = undefined;
        this.orbitMouseUpFunction = undefined;

        this.isRotating = false;
        this.rotateInitialCursorAngle = undefined;
        this.rotateFrame = undefined;
        this.rotateIsLook = false;
        this.rotateMouseMoveFunction = undefined;
        this.rotateMouseUpFunction = undefined;

        this._unsubcribeFromPostRender = undefined;

        Knockout.track(this, ['controls', 'showCompass', 'heading', 'isOrbiting', 'orbitCursorAngle', 'isRotating']);

        var that = this;


        NavigationViewModel.prototype.setNavigationLocked = function (locked)
        {
            this.navigationLocked = locked;
            if (this.controls && this.controls.length > 1)
            {
                this.controls[1].setNavigationLocked(this.navigationLocked);
            }
        };

        function widgetChange()
        {
            if (defined(that.terria))
            {
                if (that._unsubcribeFromPostRender)
                {
                    that._unsubcribeFromPostRender();
                    that._unsubcribeFromPostRender = undefined;
                }

                that.showCompass = true && that.enableCompass;

                that._unsubcribeFromPostRender = that.terria.scene.postRender.addEventListener(function ()
                {
                    that.heading = that.terria.scene.camera.heading;
                });
            }
            else
            {
                if (that._unsubcribeFromPostRender)
                {
                    that._unsubcribeFromPostRender();
                    that._unsubcribeFromPostRender = undefined;
                }
                that.showCompass = false;
            }
        }

        this.eventHelper.add(this.terria.afterWidgetChanged, widgetChange, this);
        //this.terria.afterWidgetChanged.addEventListener(widgetChange);

        widgetChange();
    };


    NavigationViewModel.prototype.destroy = function ()
    {

        this.eventHelper.removeAll();

        //loadView(require('fs').readFileSync(baseURLEmpCesium + 'js-lib/terrajs/lib/Views/Navigation.html', 'utf8'), container, this);

    };

    NavigationViewModel.prototype.show = function (container)
    {
        var testing;
        if (this.enableZoomControls && this.enableCompass)
        {
            testing = '<div class="compass" title="Drag outer ring: rotate view. ' +
                    'Drag inner gyroscope: free orbit.' +
                    'Double-click: reset view.' +
                    'TIP: You can also free orbit by holding the CTRL key and dragging the map." data-bind="visible: showCompass, event: { mousedown: handleMouseDown, dblclick: handleDoubleClick }">' +
                    '<div class="compass-outer-ring-background"></div>' +
                    ' <div class="compass-rotation-marker" data-bind="visible: isOrbiting, style: { transform: \'rotate(-\' + orbitCursorAngle + \'rad)\', \'-webkit-transform\': \'rotate(-\' + orbitCursorAngle + \'rad)\', opacity: orbitCursorOpacity }, cesiumSvgPath: { path: svgCompassRotationMarker, width: 145, height: 145 }"></div>' +
                    ' <div class="compass-outer-ring" title="Click and drag to rotate the camera" data-bind="style: { transform: \'rotate(-\' + heading + \'rad)\', \'-webkit-transform\': \'rotate(-\' + heading + \'rad)\' }, cesiumSvgPath: { path: svgCompassOuterRing, width: 145, height: 145 }"></div>' +
                    ' <div class="compass-gyro-background"></div>' +
                    ' <div class="compass-gyro" data-bind="cesiumSvgPath: { path: svgCompassGyro, width: 145, height: 145 }, css: { \'compass-gyro-active\': isOrbiting }"></div>' +
                    '</div>' +
                    '<div class="navigation-controls">' +
                    '<!-- ko foreach: controls -->' +
                    '<div data-bind="click: activate, attr: { title: $data.name }, css: $root.isLastControl($data) ? \'navigation-control-last\' : \'navigation-control\' ">' +
                    '   <!-- ko if: $data.hasText -->' +
                    '   <div data-bind="text: $data.text, css: $data.isActive ?  \'navigation-control-icon-active \' + $data.cssClass : $data.cssClass"></div>' +
                    '   <!-- /ko -->' +
                    '  <!-- ko ifnot: $data.hasText -->' +
                    '  <div data-bind="cesiumSvgPath: { path: $data.svgIcon, width: $data.svgWidth, height: $data.svgHeight }, css: $data.isActive ?  \'navigation-control-icon-active \' + $data.cssClass : $data.cssClass"></div>' +
                    '  <!-- /ko -->' +
                    ' </div>' +
                    ' <!-- /ko -->' +
                    '</div>';
        }
        else if (!this.enableZoomControls && this.enableCompass)
        {
            testing = '<div class="compass" title="Drag outer ring: rotate view. ' +
                    'Drag inner gyroscope: free orbit.' +
                    'Double-click: reset view.' +
                    'TIP: You can also free orbit by holding the CTRL key and dragging the map." data-bind="visible: showCompass, event: { mousedown: handleMouseDown, dblclick: handleDoubleClick }">' +
                    '<div class="compass-outer-ring-background"></div>' +
                    ' <div class="compass-rotation-marker" data-bind="visible: isOrbiting, style: { transform: \'rotate(-\' + orbitCursorAngle + \'rad)\', \'-webkit-transform\': \'rotate(-\' + orbitCursorAngle + \'rad)\', opacity: orbitCursorOpacity }, cesiumSvgPath: { path: svgCompassRotationMarker, width: 145, height: 145 }"></div>' +
                    ' <div class="compass-outer-ring" title="Click and drag to rotate the camera" data-bind="style: { transform: \'rotate(-\' + heading + \'rad)\', \'-webkit-transform\': \'rotate(-\' + heading + \'rad)\' }, cesiumSvgPath: { path: svgCompassOuterRing, width: 145, height: 145 }"></div>' +
                    ' <div class="compass-gyro-background"></div>' +
                    ' <div class="compass-gyro" data-bind="cesiumSvgPath: { path: svgCompassGyro, width: 145, height: 145 }, css: { \'compass-gyro-active\': isOrbiting }"></div>' +
                    '</div>' +
                    '<div class="navigation-controls"  style="display: none;" >' +
                    '<!-- ko foreach: controls -->' +
                    '<div data-bind="click: activate, attr: { title: $data.name }, css: $root.isLastControl($data) ? \'navigation-control-last\' : \'navigation-control\' ">' +
                    '   <!-- ko if: $data.hasText -->' +
                    '   <div data-bind="text: $data.text, css: $data.isActive ?  \'navigation-control-icon-active \' + $data.cssClass : $data.cssClass"></div>' +
                    '   <!-- /ko -->' +
                    '  <!-- ko ifnot: $data.hasText -->' +
                    '  <div data-bind="cesiumSvgPath: { path: $data.svgIcon, width: $data.svgWidth, height: $data.svgHeight }, css: $data.isActive ?  \'navigation-control-icon-active \' + $data.cssClass : $data.cssClass"></div>' +
                    '  <!-- /ko -->' +
                    ' </div>' +
                    ' <!-- /ko -->' +
                    '</div>';
        }
        else if (this.enableZoomControls && !this.enableCompass)
        {
            testing = '<div class="compass"  style="display: none;" title="Drag outer ring: rotate view. ' +
                    'Drag inner gyroscope: free orbit.' +
                    'Double-click: reset view.' +
                    'TIP: You can also free orbit by holding the CTRL key and dragging the map." data-bind="visible: showCompass, event: { mousedown: handleMouseDown, dblclick: handleDoubleClick }">' +
                    '<div class="compass-outer-ring-background"></div>' +
                    ' <div class="compass-rotation-marker" data-bind="visible: isOrbiting, style: { transform: \'rotate(-\' + orbitCursorAngle + \'rad)\', \'-webkit-transform\': \'rotate(-\' + orbitCursorAngle + \'rad)\', opacity: orbitCursorOpacity }, cesiumSvgPath: { path: svgCompassRotationMarker, width: 145, height: 145 }"></div>' +
                    ' <div class="compass-outer-ring" title="Click and drag to rotate the camera" data-bind="style: { transform: \'rotate(-\' + heading + \'rad)\', \'-webkit-transform\': \'rotate(-\' + heading + \'rad)\' }, cesiumSvgPath: { path: svgCompassOuterRing, width: 145, height: 145 }"></div>' +
                    ' <div class="compass-gyro-background"></div>' +
                    ' <div class="compass-gyro" data-bind="cesiumSvgPath: { path: svgCompassGyro, width: 145, height: 145 }, css: { \'compass-gyro-active\': isOrbiting }"></div>' +
                    '</div>' +
                    '<div class="navigation-controls"    >' +
                    '<!-- ko foreach: controls -->' +
                    '<div data-bind="click: activate, attr: { title: $data.name }, css: $root.isLastControl($data) ? \'navigation-control-last\' : \'navigation-control\' ">' +
                    '   <!-- ko if: $data.hasText -->' +
                    '   <div data-bind="text: $data.text, css: $data.isActive ?  \'navigation-control-icon-active \' + $data.cssClass : $data.cssClass"></div>' +
                    '   <!-- /ko -->' +
                    '  <!-- ko ifnot: $data.hasText -->' +
                    '  <div data-bind="cesiumSvgPath: { path: $data.svgIcon, width: $data.svgWidth, height: $data.svgHeight }, css: $data.isActive ?  \'navigation-control-icon-active \' + $data.cssClass : $data.cssClass"></div>' +
                    '  <!-- /ko -->' +
                    ' </div>' +
                    ' <!-- /ko -->' +
                    '</div>';
        }
        else if (!this.enableZoomControls && !this.enableCompass)
        {
            testing = '<div class="compass"  style="display: none;" title="Drag outer ring: rotate view. ' +
                    'Drag inner gyroscope: free orbit.' +
                    'Double-click: reset view.' +
                    'TIP: You can also free orbit by holding the CTRL key and dragging the map." data-bind="visible: showCompass, event: { mousedown: handleMouseDown, dblclick: handleDoubleClick }">' +
                    '<div class="compass-outer-ring-background"></div>' +
                    ' <div class="compass-rotation-marker" data-bind="visible: isOrbiting, style: { transform: \'rotate(-\' + orbitCursorAngle + \'rad)\', \'-webkit-transform\': \'rotate(-\' + orbitCursorAngle + \'rad)\', opacity: orbitCursorOpacity }, cesiumSvgPath: { path: svgCompassRotationMarker, width: 145, height: 145 }"></div>' +
                    ' <div class="compass-outer-ring" title="Click and drag to rotate the camera" data-bind="style: { transform: \'rotate(-\' + heading + \'rad)\', \'-webkit-transform\': \'rotate(-\' + heading + \'rad)\' }, cesiumSvgPath: { path: svgCompassOuterRing, width: 145, height: 145 }"></div>' +
                    ' <div class="compass-gyro-background"></div>' +
                    ' <div class="compass-gyro" data-bind="cesiumSvgPath: { path: svgCompassGyro, width: 145, height: 145 }, css: { \'compass-gyro-active\': isOrbiting }"></div>' +
                    '</div>' +
                    '<div class="navigation-controls"   style="display: none;" >' +
                    '<!-- ko foreach: controls -->' +
                    '<div data-bind="click: activate, attr: { title: $data.name }, css: $root.isLastControl($data) ? \'navigation-control-last\' : \'navigation-control\' ">' +
                    '   <!-- ko if: $data.hasText -->' +
                    '   <div data-bind="text: $data.text, css: $data.isActive ?  \'navigation-control-icon-active \' + $data.cssClass : $data.cssClass"></div>' +
                    '   <!-- /ko -->' +
                    '  <!-- ko ifnot: $data.hasText -->' +
                    '  <div data-bind="cesiumSvgPath: { path: $data.svgIcon, width: $data.svgWidth, height: $data.svgHeight }, css: $data.isActive ?  \'navigation-control-icon-active \' + $data.cssClass : $data.cssClass"></div>' +
                    '  <!-- /ko -->' +
                    ' </div>' +
                    ' <!-- /ko -->' +
                    '</div>';
        }
        loadView(testing, container, this);
        // loadView(navigatorTemplate, container, this);
        //loadView(require('fs').readFileSync(baseURLEmpCesium + 'js-lib/terrajs/lib/Views/Navigation.html', 'utf8'), container, this);

    };

    /**
     * Adds a control to this toolbar.
     * @param {NavControl} control The control to add.
     */
    NavigationViewModel.prototype.add = function (control)
    {
        this.controls.push(control);
    };

    /**
     * Removes a control from this toolbar.
     * @param {NavControl} control The control to remove.
     */
    NavigationViewModel.prototype.remove = function (control)
    {
        this.controls.remove(control);
    };

    /**
     * Checks if the control given is the last control in the control array.
     * @param {NavControl} control The control to remove.
     */
    NavigationViewModel.prototype.isLastControl = function (control)
    {
        return (control === this.controls[this.controls.length - 1]);
    };

    var vectorScratch = new Cartesian2();

    NavigationViewModel.prototype.handleMouseDown = function (viewModel, e)
    {
        var scene = this.terria.scene;
        if (scene.mode === SceneMode.MORPHING)
        {
            return true;
        }
        if (viewModel.navigationLocked)
        {
            return true;
        }

        var compassElement = e.currentTarget;
        var compassRectangle = e.currentTarget.getBoundingClientRect();
        var maxDistance = compassRectangle.width / 2.0;
        var center = new Cartesian2((compassRectangle.right - compassRectangle.left) / 2.0, (compassRectangle.bottom - compassRectangle.top) / 2.0);
        var clickLocation = new Cartesian2(e.clientX - compassRectangle.left, e.clientY - compassRectangle.top);
        var vector = Cartesian2.subtract(clickLocation, center, vectorScratch);
        var distanceFromCenter = Cartesian2.magnitude(vector);

        var distanceFraction = distanceFromCenter / maxDistance;

        var nominalTotalRadius = 145;
        var norminalGyroRadius = 50;

        if (distanceFraction < norminalGyroRadius / nominalTotalRadius)
        {
            orbit(this, compassElement, vector);
//            return false;
        }
        else if (distanceFraction < 1.0)
        {
            rotate(this, compassElement, vector);
//            return false;
        }
        else
        {
            return true;
        }
    };

    var oldTransformScratch = new Matrix4();
    var newTransformScratch = new Matrix4();
    var centerScratch = new Cartesian3();

    NavigationViewModel.prototype.handleDoubleClick = function (viewModel, e)
    {
        var scene = viewModel.terria.scene;
        var camera = scene.camera;

        var sscc = scene.screenSpaceCameraController;

        if (scene.mode == SceneMode.MORPHING || !sscc.enableInputs)
        {
            return true;
        }
        if (viewModel.navigationLocked)
        {
            return true;
        }
        if (scene.mode == SceneMode.COLUMBUS_VIEW && !sscc.enableTranslate)
        {
            return;
        }
        if (scene.mode == SceneMode.SCENE3D || scene.mode == SceneMode.COLUMBUS_VIEW)
        {
            if (!sscc.enableLook)
            {
                return;
            }

            if (scene.mode == SceneMode.SCENE3D)
            {
                if (!sscc.enableRotate)
                {
                    return
                }
            }
        }

        var center = Utils.getCameraFocus(viewModel.terria, true, centerScratch);

        if (!defined(center))
        {
            // Globe is barely visible, so reset to home view.

            this.controls[1].resetView();
            return;
        }

        var cameraPosition = scene.globe.ellipsoid.cartographicToCartesian(camera.positionCartographic, new Cartesian3());

        var surfaceNormal = scene.globe.ellipsoid.geodeticSurfaceNormal(center);

        var focusBoundingSphere = new BoundingSphere(center, 0);

        camera.flyToBoundingSphere(focusBoundingSphere, {
            offset: new HeadingPitchRange(0,
                    // do not use camera.pitch since the pitch at the center/target is required
                    CesiumMath.PI_OVER_TWO - Cartesian3.angleBetween(
                            surfaceNormal,
                            camera.directionWC
                            ),
                    // distanceToBoundingSphere returns wrong values when in 2D or Columbus view so do not use
                    // camera.distanceToBoundingSphere(focusBoundingSphere)
                    // instead calculate distance manually
                    Cartesian3.distance(cameraPosition, center)
                    ),
            duration: 1.5
        });
    };

    NavigationViewModel.create = function (options)
    {
        //options.enableZoomControls = this.enableZoomControls;
        //options.enableCompass = this.enableCompass;
        var result = new NavigationViewModel(options);
        result.show(options.container);
        return result;
    };

    function orbit(viewModel, compassElement, cursorVector)
    {
        var scene = viewModel.terria.scene;


        var sscc = scene.screenSpaceCameraController;

        // do not orbit if it is disabled
        if (scene.mode == SceneMode.MORPHING || !sscc.enableInputs)
        {
            return;
        }
        if (viewModel.navigationLocked)
        {
            return true;
        }

        switch (scene.mode)
        {
            case SceneMode.COLUMBUS_VIEW:
                if (sscc.enableLook)
                {
                    break;
                }

                if (!sscc.enableTranslate || !sscc.enableTilt)
                {
                    return;
                }
                break;
            case SceneMode.SCENE3D:
                if (sscc.enableLook)
                {
                    break;
                }

                if (!sscc.enableTilt || !sscc.enableRotate)
                {
                    return;
                }
                break;
            case SceneMode.SCENE2D:
                if (!sscc.enableTranslate)
                {
                    return;
                }
                break;
        }

        // Remove existing event handlers, if any.
        document.removeEventListener('mousemove', viewModel.orbitMouseMoveFunction, false);
        document.removeEventListener('mouseup', viewModel.orbitMouseUpFunction, false);

        if (defined(viewModel.orbitTickFunction))
        {
            viewModel.terria.clock.onTick.removeEventListener(viewModel.orbitTickFunction);
        }

        viewModel.orbitMouseMoveFunction = undefined;
        viewModel.orbitMouseUpFunction = undefined;
        viewModel.orbitTickFunction = undefined;

        viewModel.isOrbiting = true;
        viewModel.orbitLastTimestamp = getTimestamp();

        var camera = scene.camera;

        if (defined(viewModel.terria.trackedEntity))
        {
            // when tracking an entity simply use that reference frame
            viewModel.orbitFrame = undefined;
            viewModel.orbitIsLook = false;
        }
        else
        {
            var center = Utils.getCameraFocus(viewModel.terria, true, centerScratch);

            if (!defined(center))
            {
                viewModel.orbitFrame = Transforms.eastNorthUpToFixedFrame(camera.positionWC, scene.globe.ellipsoid, newTransformScratch);
                viewModel.orbitIsLook = true;
            }
            else
            {
                viewModel.orbitFrame = Transforms.eastNorthUpToFixedFrame(center, scene.globe.ellipsoid, newTransformScratch);
                viewModel.orbitIsLook = false;
            }
        }

        viewModel.orbitTickFunction = function (e)
        {
            var timestamp = getTimestamp();
            var deltaT = timestamp - viewModel.orbitLastTimestamp;
            var rate = (viewModel.orbitCursorOpacity - 0.5) * 2.5 / 1000;
            var distance = deltaT * rate;

            var angle = viewModel.orbitCursorAngle + CesiumMath.PI_OVER_TWO;
            var x = Math.cos(angle) * distance;
            var y = Math.sin(angle) * distance;

            var oldTransform;

            if (viewModel.navigationLocked)
            {
                return true;
            }

            if (defined(viewModel.orbitFrame))
            {
                oldTransform = Matrix4.clone(camera.transform, oldTransformScratch);

                camera.lookAtTransform(viewModel.orbitFrame);
            }

            // do not look up/down or rotate in 2D mode
            if (scene.mode == SceneMode.SCENE2D)
            {
                camera.move(new Cartesian3(x, y, 0), Math.max(scene.canvas.clientWidth, scene.canvas.clientHeight) / 100 * camera.positionCartographic.height * distance);
            }
            else
            {
                if (viewModel.orbitIsLook)
                {
                    camera.look(Cartesian3.UNIT_Z, -x);
                    camera.look(camera.right, -y);
                }
                else
                {
                    camera.rotateLeft(x);
                    camera.rotateUp(y);
                }
            }

            if (defined(viewModel.orbitFrame))
            {
                camera.lookAtTransform(oldTransform);
            }

            // viewModel.terria.cesium.notifyRepaintRequired();

            viewModel.orbitLastTimestamp = timestamp;
        };

        function updateAngleAndOpacity(vector, compassWidth)
        {
            var angle = Math.atan2(-vector.y, vector.x);
            viewModel.orbitCursorAngle = CesiumMath.zeroToTwoPi(angle - CesiumMath.PI_OVER_TWO);

            var distance = Cartesian2.magnitude(vector);
            var maxDistance = compassWidth / 2.0;
            var distanceFraction = Math.min(distance / maxDistance, 1.0);
            var easedOpacity = 0.5 * distanceFraction * distanceFraction + 0.5;
            viewModel.orbitCursorOpacity = easedOpacity;

            //viewModel.terria.cesium.notifyRepaintRequired();
        }

        viewModel.orbitMouseMoveFunction = function (e)
        {
            var compassRectangle = compassElement.getBoundingClientRect();
            var center = new Cartesian2((compassRectangle.right - compassRectangle.left) / 2.0, (compassRectangle.bottom - compassRectangle.top) / 2.0);
            var clickLocation = new Cartesian2(e.clientX - compassRectangle.left, e.clientY - compassRectangle.top);
            var vector = Cartesian2.subtract(clickLocation, center, vectorScratch);
            updateAngleAndOpacity(vector, compassRectangle.width);
        };

        viewModel.orbitMouseUpFunction = function (e)
        {
            // TODO: if mouse didn't move, reset view to looking down, north is up?

            viewModel.isOrbiting = false;
            document.removeEventListener('mousemove', viewModel.orbitMouseMoveFunction, false);
            document.removeEventListener('mouseup', viewModel.orbitMouseUpFunction, false);

            if (defined(viewModel.orbitTickFunction))
            {
                viewModel.terria.clock.onTick.removeEventListener(viewModel.orbitTickFunction);
            }

            viewModel.orbitMouseMoveFunction = undefined;
            viewModel.orbitMouseUpFunction = undefined;
            viewModel.orbitTickFunction = undefined;
        };

        document.addEventListener('mousemove', viewModel.orbitMouseMoveFunction, false);
        document.addEventListener('mouseup', viewModel.orbitMouseUpFunction, false);
        viewModel.terria.clock.onTick.addEventListener(viewModel.orbitTickFunction);

        updateAngleAndOpacity(cursorVector, compassElement.getBoundingClientRect().width);
    }

    function rotate(viewModel, compassElement, cursorVector)
    {
        var scene = viewModel.terria.scene;
        var camera = scene.camera;

        var sscc = scene.screenSpaceCameraController;
        // do not rotate in 2D mode or if rotating is disabled
        if (scene.mode == SceneMode.MORPHING || scene.mode == SceneMode.SCENE2D || !sscc.enableInputs)
        {
            return;
        }
        if (viewModel.navigationLocked)
        {
            return true;
        }

        if (!sscc.enableLook && (scene.mode == SceneMode.COLUMBUS_VIEW || (scene.mode == SceneMode.SCENE3D && !sscc.enableRotate)))
        {
            return;
        }

        // Remove existing event handlers, if any.
        document.removeEventListener('mousemove', viewModel.rotateMouseMoveFunction, false);
        document.removeEventListener('mouseup', viewModel.rotateMouseUpFunction, false);

        viewModel.rotateMouseMoveFunction = undefined;
        viewModel.rotateMouseUpFunction = undefined;

        viewModel.isRotating = true;
        viewModel.rotateInitialCursorAngle = Math.atan2(-cursorVector.y, cursorVector.x);

        if (defined(viewModel.terria.trackedEntity))
        {
            // when tracking an entity simply use that reference frame
            viewModel.rotateFrame = undefined;
            viewModel.rotateIsLook = false;
        }
        else
        {
            var viewCenter = Utils.getCameraFocus(viewModel.terria, true, centerScratch);

            if (!defined(viewCenter) || (scene.mode == SceneMode.COLUMBUS_VIEW && !sscc.enableLook && !sscc.enableTranslate))
            {
                viewModel.rotateFrame = Transforms.eastNorthUpToFixedFrame(camera.positionWC, scene.globe.ellipsoid, newTransformScratch);
                viewModel.rotateIsLook = true;
            }
            else
            {
                viewModel.rotateFrame = Transforms.eastNorthUpToFixedFrame(viewCenter, scene.globe.ellipsoid, newTransformScratch);
                viewModel.rotateIsLook = false;
            }
        }

        var oldTransform;
        if (defined(viewModel.rotateFrame))
        {
            oldTransform = Matrix4.clone(camera.transform, oldTransformScratch);
            camera.lookAtTransform(viewModel.rotateFrame);
        }

        viewModel.rotateInitialCameraAngle = -camera.heading;

        if (defined(viewModel.rotateFrame))
        {
            camera.lookAtTransform(oldTransform);
        }

        viewModel.rotateMouseMoveFunction = function (e)
        {
            var compassRectangle = compassElement.getBoundingClientRect();
            var center = new Cartesian2((compassRectangle.right - compassRectangle.left) / 2.0, (compassRectangle.bottom - compassRectangle.top) / 2.0);
            var clickLocation = new Cartesian2(e.clientX - compassRectangle.left, e.clientY - compassRectangle.top);
            var vector = Cartesian2.subtract(clickLocation, center, vectorScratch);
            var angle = Math.atan2(-vector.y, vector.x);

            var angleDifference = angle - viewModel.rotateInitialCursorAngle;
            var newCameraAngle = CesiumMath.zeroToTwoPi(viewModel.rotateInitialCameraAngle - angleDifference);

            var camera = viewModel.terria.scene.camera;

            var oldTransform;
            if (defined(viewModel.rotateFrame))
            {
                oldTransform = Matrix4.clone(camera.transform, oldTransformScratch);
                camera.lookAtTransform(viewModel.rotateFrame);
            }

            var currentCameraAngle = -camera.heading;
            camera.rotateRight(newCameraAngle - currentCameraAngle);

            if (defined(viewModel.rotateFrame))
            {
                camera.lookAtTransform(oldTransform);
            }

            // viewModel.terria.cesium.notifyRepaintRequired();
        };

        viewModel.rotateMouseUpFunction = function (e)
        {
            viewModel.isRotating = false;
            document.removeEventListener('mousemove', viewModel.rotateMouseMoveFunction, false);
            document.removeEventListener('mouseup', viewModel.rotateMouseUpFunction, false);

            viewModel.rotateMouseMoveFunction = undefined;
            viewModel.rotateMouseUpFunction = undefined;
        };

        document.addEventListener('mousemove', viewModel.rotateMouseMoveFunction, false);
        document.addEventListener('mouseup', viewModel.rotateMouseUpFunction, false);
    }

    return NavigationViewModel;
});

/*global define*/
define('CesiumNavigation',[
    'Cesium/Core/defined',
//    'Cesium/Core/defaultValue',
    'Cesium/Core/Event',
    'KnockoutES5',
    'Core/registerKnockoutBindings',
    'ViewModels/DistanceLegendViewModel',
    'ViewModels/NavigationViewModel'
], function (
        defined,
//    defaultValue,
        CesiumEvent,
        Knockout,
        registerKnockoutBindings,
        DistanceLegendViewModel,
        NavigationViewModel)
{
    'use strict';

    /**
     * @alias CesiumNavigation
     * @constructor
     *
     * @param {Viewer|CesiumWidget} viewerCesiumWidget The Viewer or CesiumWidget instance
     */
    var CesiumNavigation = function (viewerCesiumWidget) {
        initialize.apply(this, arguments);

        this._onDestroyListeners = [];
    };

    CesiumNavigation.prototype.distanceLegendViewModel = undefined;
    CesiumNavigation.prototype.navigationViewModel = undefined;
    CesiumNavigation.prototype.navigationDiv = undefined;
    CesiumNavigation.prototype.distanceLegendDiv = undefined;
    CesiumNavigation.prototype.terria = undefined;
    CesiumNavigation.prototype.container = undefined;
    CesiumNavigation.prototype._onDestroyListeners = undefined;
    CesiumNavigation.prototype._navigationLocked = false;
    
     CesiumNavigation.prototype.setNavigationLocked = function ( locked)
    {
        this._navigationLocked = locked;
        this.navigationViewModel.setNavigationLocked( this._navigationLocked );
        
    };
    
     CesiumNavigation.prototype.getNavigationLocked = function ()
    {
        return this._navigationLocked  ;
    };

    CesiumNavigation.prototype.destroy = function ()
    {
        if (defined(this.navigationViewModel))
        {
            this.navigationViewModel.destroy();
        }
        if (defined(this.distanceLegendViewModel))
        {
            this.distanceLegendViewModel.destroy();
        }

        if (defined(this.navigationDiv))
        {
            this.navigationDiv.parentNode.removeChild(this.navigationDiv);
        }
        delete this.navigationDiv;

        if (defined(this.distanceLegendDiv))
        {
            this.distanceLegendDiv.parentNode.removeChild(this.distanceLegendDiv);
        }
        delete this.distanceLegendDiv;

        if (defined(this.container))
        {
            this.container.parentNode.removeChild(this.container);
        }
        delete this.container;

        for (var i = 0; i < this._onDestroyListeners.length; i++)
        {
            this._onDestroyListeners[i]();
        }
    };

    CesiumNavigation.prototype.addOnDestroyListener = function (callback)
    {
        if (typeof callback === "function")
        {
            this._onDestroyListeners.push(callback);
        }
    };

    /**
     * @param {Viewer|CesiumWidget} viewerCesiumWidget The Viewer or CesiumWidget instance
     * @param options
     */
    function initialize(viewerCesiumWidget, options) {
        if (!defined(viewerCesiumWidget)) {
            throw new DeveloperError('CesiumWidget or Viewer is required.');
        }

//        options = defaultValue(options, defaultValue.EMPTY_OBJECT);

        var cesiumWidget = defined(viewerCesiumWidget.cesiumWidget) ? viewerCesiumWidget.cesiumWidget : viewerCesiumWidget;

        var container = document.createElement('div');
        container.className = 'cesium-widget-cesiumNavigationContainer';
        cesiumWidget.container.appendChild(container);

        this.terria = viewerCesiumWidget;
        this.terria.options = (defined(options))?options :{};
        this.terria.afterWidgetChanged = new CesiumEvent();
        this.terria.beforeWidgetChanged = new CesiumEvent();
        this.container = container;
        
        //this.navigationDiv.setAttribute("id", "navigationDiv");
        
           
          // Register custom Knockout.js bindings.  If you're not using the TerriaJS user interface, you can remove this.
        registerKnockoutBindings();

        if (!defined(this.terria.options.enableDistanceLegend) || this.terria.options.enableDistanceLegend)
        {
            this.distanceLegendDiv = document.createElement('div');
             container.appendChild(this.distanceLegendDiv);
            this.distanceLegendDiv.setAttribute("id", "distanceLegendDiv");
            this.distanceLegendViewModel = DistanceLegendViewModel.create({
                container: this.distanceLegendDiv,
                terria: this.terria,
                mapElement: container,
                enableDistanceLegend: true
            });
           
        }
     

        if ((!defined(this.terria.options.enableZoomControls) || this.terria.options.enableZoomControls) && (!defined(this.terria.options.enableCompass) || this.terria.options.enableCompass))
        {
            this.navigationDiv = document.createElement('div');
            this.navigationDiv.setAttribute("id", "navigationDiv");
            container.appendChild(this.navigationDiv);
            // Create the navigation controls.
            this.navigationViewModel = NavigationViewModel.create({
                container: this.navigationDiv,
                terria: this.terria,
                enableZoomControls: true,
                enableCompass: true
            });
        }
        else  if ((defined(this.terria.options.enableZoomControls) && !this.terria.options.enableZoomControls) && (!defined(this.terria.options.enableCompass) || this.terria.options.enableCompass))
        {
            this.navigationDiv = document.createElement('div');
            this.navigationDiv.setAttribute("id", "navigationDiv");
            container.appendChild(this.navigationDiv);
            // Create the navigation controls.
            this.navigationViewModel = NavigationViewModel.create({
                container: this.navigationDiv,
                terria: this.terria,
                enableZoomControls: false,
                enableCompass: true
            });
        }
        else  if ((!defined(this.terria.options.enableZoomControls) || this.terria.options.enableZoomControls) && (defined(this.terria.options.enableCompass) && !this.terria.options.enableCompass))
        {
            this.navigationDiv = document.createElement('div');
            this.navigationDiv.setAttribute("id", "navigationDiv");
            container.appendChild(this.navigationDiv);
            // Create the navigation controls.
            this.navigationViewModel = NavigationViewModel.create({
                container: this.navigationDiv,
                terria: this.terria,
                enableZoomControls: true,
                enableCompass: false
            });
        }
        else  if ((defined(this.terria.options.enableZoomControls) &&  !this.terria.options.enableZoomControls) && (defined(this.terria.options.enableCompass) &&  !this.terria.options.enableCompass))
        {
            //this.navigationDiv.setAttribute("id", "navigationDiv");
           // container.appendChild(this.navigationDiv);
            // Create the navigation controls.
//            this.navigationViewModel = NavigationViewModel.create({
//                container: this.navigationDiv,
//                terria: this.terria,
//                enableZoomControls: false,
//                enableCompass: false
//            });
        }

    }

    return CesiumNavigation;
});


define('dummy/require-less/less/dummy',[],function(){});
/**
 * Created by Larcius on 18.02.16.
 */
/*global define*/
define('viewerCesiumNavigationMixin',[
    'Cesium/Core/defined',
    'Cesium/Core/DeveloperError',
    'CesiumNavigation',
    'dummy/require-less/less/dummy'
], function(
    defined,
    DeveloperError,
    CesiumNavigation) {
    'use strict';

    /**
     * A mixin which adds the Compass/Navigation widget to the Viewer widget.
     * Rather than being called directly, this function is normally passed as
     * a parameter to {@link Viewer#extend}, as shown in the example below.
     * @exports viewerCesiumNavigationMixin
     *
     * @param {Viewer} viewer The viewer instance.
     * @param {{}} options The options.
     *
     * @exception {DeveloperError} viewer is required.
     *
     * @demo {@link http://localhost:8080/index.html|run local server with examples}
     *
     * @example
     * var viewer = new Cesium.Viewer('cesiumContainer');
     * viewer.extend(viewerCesiumNavigationMixin);
     */
    function viewerCesiumNavigationMixin(viewer, options) {
        if (!defined(viewer)) {
            throw new DeveloperError('viewer is required.');
        }

        var cesiumNavigation = init(viewer, options);

        cesiumNavigation.addOnDestroyListener((function (viewer) {
            return function () {
                delete viewer.cesiumNavigation;
            };
        })(viewer));

        Object.defineProperties(viewer, {
            cesiumNavigation: {
                configurable: true,
                get: function () {
                    return viewer.cesiumWidget.cesiumNavigation;
                }
            }
        });
    }

    /**
     *
     * @param {CesiumWidget} cesiumWidget The cesium widget instance.
     * @param {{}} options The options.
     */
    viewerCesiumNavigationMixin.mixinWidget = function (cesiumWidget, options) {
        return init.apply(undefined, arguments);
    };

    /**
     * @param {Viewer|CesiumWidget} viewerCesiumWidget The Viewer or CesiumWidget instance
     * @param {{}} options the options
     */
    var init = function (viewerCesiumWidget, options) {
        var cesiumNavigation = new CesiumNavigation(viewerCesiumWidget, options);

        var cesiumWidget = defined(viewerCesiumWidget.cesiumWidget) ? viewerCesiumWidget.cesiumWidget : viewerCesiumWidget;

        Object.defineProperties(cesiumWidget, {
            cesiumNavigation: {
                configurable: true,
                get: function () {
                    return cesiumNavigation;
                }
            }
        });

        cesiumNavigation.addOnDestroyListener((function (cesiumWidget) {
            return function () {
                delete cesiumWidget.cesiumNavigation;
            };
        })(cesiumWidget));

        return cesiumNavigation;
    };

    return viewerCesiumNavigationMixin;
});


(function(c){var d=document,a='appendChild',i='styleSheet',s=d.createElement('style');s.type='text/css';d.getElementsByTagName('head')[0][a](s);s[i]?s[i].cssText=c:s[a](d.createTextNode(c));})
('/*html {\n    height: 100%;\n    -webkit-font-smoothing: antialiased;\n}\n\nbody {\n    height: 100%;\n    width: 100%;\n    margin: 0;\n    overflow: hidden;\n    padding: 0;\n    background: #000;\n    font-size: 15px;\n    font-family: @default-font;\n}*/\n.full-window {\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  bottom: 0;\n  margin: 0;\n  overflow: hidden;\n  padding: 0;\n  -webkit-transition: left 0.25s ease-out;\n  -moz-transition: left 0.25s ease-out;\n  -ms-transition: left 0.25s ease-out;\n  -o-transition: left 0.25s ease-out;\n  transition: left 0.25s ease-out;\n}\n.transparent-to-input {\n  pointer-events: none;\n}\n.opaque-to-input {\n  pointer-events: auto;\n}\n.clickable {\n  cursor: pointer;\n}\n/*a {\n    text-decoration: none;\n    color: @highlight-color;\n}*/\na:hover {\n  text-decoration: underline;\n}\n/*\n@modal-background-color: @panel-background-color;\n@modal-text-color: @panel-emphasized-text-color;\n@modal-header-background-color: rgba(0,0,0,0.2);\n@modal-header-text-color: @panel-emphasized-text-color;*/\n/*.modal-background {\n    .opaque-to-input;\n    position: fixed;\n    left: 0;\n    right: 0;\n    top: 0;\n    bottom: 0;\n    background-color: rgba(0,0,0,0.5);\n    z-index: 1000;  required for IE9 \n}*/\n/*\n.modal {\n    position: absolute;\n    margin: auto;\n    background-color: @modal-background-color;\n    top: 0;\n    left: 0;\n    bottom: 0;\n    right: 0;\n    max-height: 100%;\n    max-width: 100%;\n    font-family: @default-font;\n    color: @modal-text-color;\n}\n\n.modal-header {\n  background-color: @modal-header-background-color;\n  border-bottom: @panel-element-border;\n  font-size: 15px;\n  line-height: 40px;\n  margin: 0;\n}\n\n.modal-header h1 {\n  font-size: 15px;\n  color: @modal-header-text-color;\n  margin-left: 15px;\n}*/\n/* Commented out due to conflicts with client apps. \n.modal-content {\n  margin-left: 15px;\n  margin-right: 15px;\n  margin-bottom: 15px;\n  padding-top: 15px;\n  overflow: auto;\n}*/\n/*.modal-close-button {\n    position: absolute;\n    right: 15px;\n    cursor: pointer;\n    font-size: 18px;\n    color: @modal-header-text-color;\n}*/\n#ui {\n  z-index: 2100;\n}\n@media print {\n  .full-window {\n    position: initial;\n  }\n}\n/* input[type=text] {\n  height: 38px;\n  background-color: #eeeeee;\n  color: @input-text-color;\n  font-size: 14px;\n}\n\n::-webkit-input-placeholder {\n  color: fade(@input-text-color, 75%);\n  font-style: italic;\n}\n\n:-moz-placeholder { /* Firefox 18- \n  color: fade(@input-text-color, 75%);\n  font-style: italic;\n}\n\n::-moz-placeholder {  /* Firefox 19+  \n  color: fade(@input-text-color, 75%);\n  font-style: italic;\n}\n\n:-ms-input-placeholder {\n  color: fade(@input-text-color, 75%);\n  font-style: italic;\n}\n\ninput:focus {\n    outline-color: #FFFFFF;\n}\n*/\n/*select {\n  display: block;\n  background-color: @panel-form-input-background-color;\n  color: @panel-form-input-text-color;\n  height: 40px;\n  border: 0;\n  margin-top: 10px;\n  font-size: 14px;\n  padding-left: 5px;\n}*/\n.markdown img {\n  max-width: 100%;\n}\n.markdown svg {\n  max-height: 100%;\n}\n.markdown input,\n.markdown select,\n.markdown textarea,\n.markdown fieldset {\n  font-family: inherit;\n  font-size: 1rem;\n  box-sizing: border-box;\n  margin-top: 0;\n  margin-bottom: 0;\n}\n.markdown label {\n  vertical-align: middle;\n}\n.markdown h1,\n.markdown h2,\n.markdown h3,\n.markdown h4,\n.markdown h5,\n.markdown h6 {\n  font-family: inherit;\n  font-weight: bold;\n  line-height: 1.25;\n  margin-top: 1em;\n  margin-bottom: .5em;\n}\n.markdown h1 {\n  font-size: 2rem;\n}\n.markdown h2 {\n  font-size: 1.5rem;\n}\n.markdown h3 {\n  font-size: 1.25rem;\n}\n.markdown h4 {\n  font-size: 1rem;\n}\n.markdown h5 {\n  font-size: 0.875rem;\n}\n.markdown h6 {\n  font-size: 0.75rem;\n}\n.markdown p {\n  margin-top: 0;\n  margin-bottom: 1rem;\n}\n.markdown strong {\n  font-weight: bold;\n}\n.markdown em {\n  font-style: italic;\n}\n.markdown small {\n  font-size: 80%;\n}\n.markdown mark {\n  color: #000;\n  background: #ff0;\n}\n.markdown u {\n  text-decoration: underline;\n}\n.markdown s {\n  text-decoration: line-through;\n}\n.markdown dl,\n.markdown ol,\n.markdown ul {\n  margin-top: 0;\n  margin-bottom: 1rem;\n}\n.markdown ol {\n  list-style: decimal inside;\n}\n.markdown ul {\n  list-style: disc inside;\n}\n.markdown pre,\n.markdown code,\n.markdown samp {\n  font-family: monospace;\n  font-size: inherit;\n}\n.markdown pre {\n  margin-top: 0;\n  margin-bottom: 1rem;\n  overflow-x: scroll;\n}\n.markdown a {\n  color: #68ADFE;\n  text-decoration: none;\n}\n.markdown a:hover {\n  text-decoration: underline;\n}\n.markdown pre,\n.markdown code {\n  background-color: transparent;\n  border-radius: 3px;\n}\n.markdown hr {\n  border: 0;\n  border-bottom-style: solid;\n  border-bottom-width: 1px;\n  border-bottom-color: rgba(0, 0, 0, 0.125);\n}\n.markdown .left-align {\n  text-align: left;\n}\n.markdown .center {\n  text-align: center;\n}\n.markdown .right-align {\n  text-align: right;\n}\n.markdown .justify {\n  text-align: justify;\n}\n.markdown .truncate {\n  max-width: 100%;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n}\n.markdown ol.upper-roman {\n  list-style-type: upper-roman;\n}\n.markdown ol.lower-alpha {\n  list-style-type: lower-alpha;\n}\n.markdown ul.circle {\n  list-style-type: circle;\n}\n.markdown ul.square {\n  list-style-type: square;\n}\n.markdown .list-reset {\n  list-style: none;\n  padding-left: 0;\n}\n.floating {\n  pointer-events: auto;\n  position: absolute;\n  border-radius: 15px;\n  background-color: rgba(47, 53, 60, 0.8);\n}\n.floating-horizontal {\n  pointer-events: auto;\n  position: absolute;\n  border-radius: 15px;\n  background-color: rgba(47, 53, 60, 0.8);\n  padding-left: 5px;\n  padding-right: 5px;\n}\n.floating-vertical {\n  pointer-events: auto;\n  position: absolute;\n  border-radius: 15px;\n  background-color: rgba(47, 53, 60, 0.8);\n  padding-top: 5px;\n  padding-bottom: 5px;\n}\n@media print {\n  .floating {\n    display: none;\n  }\n}\n.distance-legend {\n  pointer-events: auto;\n  position: absolute;\n  border-radius: 15px;\n  background-color: rgba(47, 53, 60, 0.8);\n  padding-left: 5px;\n  padding-right: 5px;\n  right: 25px;\n  bottom: 30px;\n  height: 30px;\n  width: 125px;\n  border: 1px solid rgba(255, 255, 255, 0.1);\n  box-sizing: content-box;\n}\n.distance-legend-label {\n  display: inline-block;\n  font-family: \'Roboto\', sans-serif;\n  font-size: 14px;\n  font-weight: lighter;\n  line-height: 30px;\n  color: #ffffff;\n  width: 125px;\n  text-align: center;\n}\n.distance-legend-scale-bar {\n  border-left: 1px solid #ffffff;\n  border-right: 1px solid #ffffff;\n  border-bottom: 1px solid #ffffff;\n  position: absolute;\n  height: 10px;\n  top: 15px;\n}\n@media print {\n  .distance-legend {\n    display: none;\n  }\n}\n@media screen and (max-width: 700px), screen and (max-height: 420px) {\n  .distance-legend {\n    display: none;\n  }\n}\n.navigation-controls {\n  position: absolute;\n  right: 30px;\n  top: 210px;\n  width: 30px;\n  border: 1px solid rgba(255, 255, 255, 0.1);\n  font-weight: 300;\n  -webkit-touch-callout: none;\n  -webkit-user-select: none;\n  -khtml-user-select: none;\n  -moz-user-select: none;\n  -ms-user-select: none;\n  user-select: none;\n}\n.navigation-control {\n  cursor: pointer;\n  border-bottom: 1px solid #555555;\n}\n.naviagation-control:active {\n  color: #FFF;\n}\n.navigation-control-last {\n  cursor: pointer;\n  border-bottom: 1px solid #555555;\n  border-bottom: 0;\n}\n.navigation-control-icon-zoom-in {\n  position: relative;\n  text-align: center;\n  font-size: 20px;\n  color: #ffffff;\n  padding-bottom: 4px;\n}\n.navigation-control-icon-zoom-out {\n  position: relative;\n  text-align: center;\n  font-size: 20px;\n  color: #ffffff;\n}\n.navigation-control-icon-reset {\n  position: relative;\n  left: 10px;\n  width: 10px;\n  height: 10px;\n  fill: rgba(255, 255, 255, 0.8);\n  padding-top: 6px;\n  padding-bottom: 6px;\n  box-sizing: content-box;\n}\n.compass {\n  pointer-events: auto;\n  position: absolute;\n  right: 0px;\n  top: 100px;\n  width: 95px;\n  height: 95px;\n  overflow: hidden;\n}\n.compass-outer-ring {\n  position: absolute;\n  top: 0;\n  width: 95px;\n  height: 95px;\n  fill: rgba(255, 255, 255, 0.5);\n}\n.compass-outer-ring-background {\n  position: absolute;\n  top: 14px;\n  left: 14px;\n  width: 44px;\n  height: 44px;\n  border-radius: 44px;\n  border: 12px solid rgba(47, 53, 60, 0.8);\n  box-sizing: content-box;\n}\n.compass-gyro {\n  pointer-events: none;\n  position: absolute;\n  top: 0;\n  width: 95px;\n  height: 95px;\n  fill: #CCC;\n}\n.compass-gyro-active {\n  fill: #68adfe;\n}\n.compass-gyro-background {\n  position: absolute;\n  top: 30px;\n  left: 30px;\n  width: 33px;\n  height: 33px;\n  border-radius: 33px;\n  background-color: rgba(47, 53, 60, 0.8);\n  border: 1px solid rgba(255, 255, 255, 0.2);\n  box-sizing: content-box;\n}\n.compass-gyro-background:hover + .compass-gyro {\n  fill: #68adfe;\n}\n.compass-rotation-marker {\n  position: absolute;\n  top: 0;\n  width: 95px;\n  height: 95px;\n  fill: #68adfe;\n}\n@media screen and (max-width: 700px), screen and (max-height: 420px) {\n  .navigation-controls {\n    display: none;\n  }\n  .compass {\n    display: none;\n  }\n}\n@media print {\n  .navigation-controls {\n    display: none;\n  }\n  .compass {\n    display: none;\n  }\n}\n');


// actual code -->

    /*global define,require,self,Cesium*/
    
define('Cesium/Core/defined', function() { return Cesium['defined']; });
define('Cesium/Core/defaultValue', function() { return Cesium['defaultValue']; });
define('Cesium/Core/Event', function() { return Cesium['Event']; });
define('Cesium/Widgets/getElement', function() { return Cesium['getElement']; });
define('Cesium/Widgets/SvgPathBindingHandler', function() { return Cesium['SvgPathBindingHandler']; });
define('Cesium/Core/Ray', function() { return Cesium['Ray']; });
define('Cesium/Core/Cartesian3', function() { return Cesium['Cartesian3']; });
define('Cesium/Core/Cartographic', function() { return Cesium['Cartographic']; });
define('Cesium/Core/ReferenceFrame', function() { return Cesium['ReferenceFrame']; });
define('Cesium/Scene/SceneMode', function() { return Cesium['SceneMode']; });
define('Cesium/Core/DeveloperError', function() { return Cesium['DeveloperError']; });
define('Cesium/Core/EllipsoidGeodesic', function() { return Cesium['EllipsoidGeodesic']; });
define('Cesium/Core/Cartesian2', function() { return Cesium['Cartesian2']; });
define('Cesium/Core/getTimestamp', function() { return Cesium['getTimestamp']; });
define('Cesium/Core/EventHelper', function() { return Cesium['EventHelper']; });
define('Cesium/Core/Math', function() { return Cesium['Math']; });
define('Cesium/Core/Transforms', function() { return Cesium['Transforms']; });
define('Cesium/Core/Matrix4', function() { return Cesium['Matrix4']; });
define('Cesium/Core/BoundingSphere', function() { return Cesium['BoundingSphere']; });
define('Cesium/Core/HeadingPitchRange', function() { return Cesium['HeadingPitchRange']; });
define('Cesium/Scene/Camera', function() { return Cesium['Camera']; });
define('Cesium/Core/Rectangle', function() { return Cesium['Rectangle']; });
define('Cesium/Core/IntersectionTests', function() { return Cesium['IntersectionTests']; });
    
    var mixin = require('viewerCesiumNavigationMixin');
    if (typeof Cesium === 'object' && Cesium !== null) {
        Cesium['viewerCesiumNavigationMixin'] = mixin;
    }

    return mixin;}));
;
///<jscompress sourcefile="ODLineMaterial.js" />
Cesium.ODLineMaterial=function (color, duration,direction,effect,url) {
    this._definitionChanged = new Cesium.Event();
    this._color = undefined;
    this._colorSubscription = undefined;
    this.color = color;
    this.duration = duration;
    this.direction = direction||1;
    this.effect = effect||0;
    this._time = (new Date()).getTime();
    this._url = url||undefined;
    this._LinkType = VFG.Util.getUuid();
    this._source =this.getSource();
    var _this=this;
    Cesium.Material._materialCache.addMaterial(_this._LinkType, {
        fabric: {
            type: _this._LinkType,
            uniforms: {
                color: new Cesium.Color(1.0, 0.0, 0.0, 0.5),
                image: _this._url,
                time: 0,
                repeat: new Cesium.Cartesian2(1.0, 1.0),
                direction:1
            },
            source: _this._source
          },
          translucent: function (material) {
            return true;
          }
    })
}

Object.defineProperties(Cesium.ODLineMaterial.prototype, {
    isConstant: {
        get: function () {
            return false;
        }
    },
    definitionChanged: {
        get: function () {
            return this._definitionChanged;
        }
    },
    color: Cesium.createPropertyDescriptor('color')
});
        
Cesium.ODLineMaterial.prototype.getType = function (time) {
    return this._LinkType;
}
Cesium.ODLineMaterial.prototype.getValue = function (time, result) {
    if (!Cesium.defined(result)) {
        result = {};
    }
    result.color = Cesium.Property.getValueOrClonedDefault(this._color, time, Cesium.Color.WHITE, result.color);
    result.image = this._url;
    result.time = (((new Date()).getTime() - this._time) % this.duration) / this.duration;
    return result;
}    
Cesium.ODLineMaterial.prototype.equals = function (other) {
    return this === other || (other instanceof Cesium.ODLineMaterial && Cesium.Property.equals(this._color, other._color))
};

Cesium.ODLineMaterial.prototype.getSource = function () {
	if("0"==this.effect){
		return "czm_material czm_getMaterial(czm_materialInput materialInput)\n\
	        {\n\
	        czm_material material = czm_getDefaultMaterial(materialInput);\n\
	        vec2 st = repeat * materialInput.st;\n\
	        vec4 colorImage = texture2D(image, vec2(fract(direction*st.s - time), st.t));\n\
	        if(color.a == 0.0)\n\
	        {\n\
	            material.alpha = colorImage.a;\n\
	            material.diffuse = colorImage.rgb; \n\
				material.specular = 1.0;\n\
	    		material.shininess = .8;\n\
	        }\n\
	        else\n\
	        {\n\
	            material.alpha = colorImage.a * color.a;\n\
	            material.diffuse = max(color.rgb * material.alpha * 3.0, color.rgb); \n\
				material.specular = 1.0;\n\
				material.shininess = .8;\n\
	        }\n\
	        return material;\n\
	    }";
	}
	else if("1"==this.effect){
		return "czm_material czm_getMaterial(czm_materialInput materialInput)\n\
		    {\n\
		        czm_material material = czm_getDefaultMaterial(materialInput);\n\
		        vec2 st = repeat * materialInput.st;\n\
		        vec4 colorImage = texture2D(image, vec2(fract(direction*st.s - time), st.t));\n\
		        if(color.a == 0.0)\n\
		        {\n\
		            material.alpha = colorImage.a;\n\
		            material.diffuse = colorImage.rgb; \n\
					material.specular = 1.0;\n\
		    		material.shininess = .8;\n\
		        }\n\
		        else\n\
		        {\n\
		            material.alpha = colorImage.a * color.a;\n\
		            material.diffuse = max(color.rgb * material.alpha * 3.0, color.rgb); \n\
					material.specular = 1.0;\n\
					material.shininess = .8;\n\
		        }\n\
		        return material;\n\
		    }"
	}
	else if("2"==this.effect){
		return 	"czm_material czm_getMaterial(czm_materialInput materialInput)\n\
		    {\n\
		        czm_material material = czm_getDefaultMaterial(materialInput);\n\
		        vec2 st = repeat * materialInput.st;\n\
		        vec4 colorImage = texture2D(image, vec2(fract(direction*st.s - time), st.t));\n\
		        if(color.a == 0.0)\n\
		        {\n\
		            material.alpha = colorImage.a;\n\
		            material.diffuse = colorImage.rgb; \n\
					material.specular = 1.0;\n\
		    		material.shininess = .8;\n\
		        }\n\
		        else\n\
		        {\n\
		            material.alpha = colorImage.a * color.a;\n\
		            material.diffuse = max(color.rgb * material.alpha * 3.0, color.rgb); \n\
					material.specular = 1.0;\n\
					material.shininess = .8;\n\
		        }\n\
		        return material;\n\
		    }"
	}
};
 

;
///<jscompress sourcefile="CesiumEcefLlhEnu.js" />

/*  *  *  *  *  *  *  *  *  *  *
 *     对cesium分析的扩展      *
 *  *  *  *  *  *  *  *  *  *  */
!function(e, t) {
	"object" == typeof exports && "object" == typeof module ? module.exports = t(require("Cesium"))
			: "function" == typeof define && define.amd ? define([ "Cesium" ],
					t)
					: "object" == typeof exports ? exports.CesiumAnalysi = t(require("Cesium"))
							: e.CesiumAnalysi = t(e.Cesium)
}("undefined" != typeof self ? self : this, function(cesium) {
	function _() {
	    this.PI = 3.141592653589793238;
	    this.a = 6378137.0;
	    this.b = 6356752.3142
	    this.f = (this.a - this.b) / this.a;
	    this.e_sq = this.f * (2.0 - this.f);
	    this.ee = 0.00669437999013;
	    this.WGSF = 1 / 298.257223563;
	    this.WGSe2 = this.WGSF * (2 - this.WGSF);
	    this.WGSa = 6378137.00000;
	    this.EPSILON = 1.0e-12;
	}
	 _.prototype.CalculateCoordinates = function (point, azimuth, elevation, distance) {
	    var vertical_height = distance * Math.sin(2 * this.PI / 360 * elevation);//垂直高度
	    var  horizontal_distance = distance * Math.cos(2 * this.PI / 360 * elevation);//水平距离
	    if (azimuth > 360) azimuth = azimuth % 360;
	    if (azimuth < 0) azimuth = 360 + (azimuth % 360);

	    var point = this.lonLat2WebMercator(point);
	    var lnglat = null;

	    if (azimuth <= 90) {//第四象限
	    	var x_length = horizontal_distance * Math.cos(2 * this.PI / 360 * azimuth);
	    	var y_length = horizontal_distance * Math.sin(2 * this.PI / 360 * azimuth);
	        lnglat = {
	            x: point.x + x_length,
	            y: point.y - y_length
	        }
	    } else if (azimuth > 90 && azimuth <= 180) {//第三象限
	    	var x_length = horizontal_distance * Math.sin(2 * this.PI / 360 * (azimuth - 90));
	    	var y_length = horizontal_distance * Math.cos(2 * this.PI / 360 * (azimuth - 90));
	        lnglat = {
	            x: point.x - x_length,
	            y: point.y - y_length
	        }
	    } else if (azimuth > 180 && azimuth <= 270) {//第二象限
	    	var x_length = horizontal_distance * Math.cos(2 * this.PI / 360 * (azimuth - 180));
	    	var y_length = horizontal_distance * Math.sin(2 * this.PI / 360 * (azimuth - 180));
	        lnglat = {
	            x: point.x - x_length,
	            y: point.y + y_length
	        }
	    } else {//第一象限
	    	var x_length = horizontal_distance * Math.sin(2 * this.PI / 360 * (azimuth - 270));
	    	var y_length = horizontal_distance * Math.cos(2 * this.PI / 360 * (azimuth - 270));
	        lnglat = {
	            x: point.x + x_length,
	            y: point.y + y_length
	        }
	    }
	    lnglat = this.webMercator2LonLat(lnglat);
	    return {
	        lng: lnglat.x,
	        lat: lnglat.y,
	        height: vertical_height
	    }
	}
	 /*
	    *经纬度转Web墨卡托
	    *@lonLat 经纬度
	    */
	 _.prototype.lonLat2WebMercator = function (lonLat) {
	    let x = lonLat.x * this.a / 180;
	    let y = Math.log(Math.tan((90 + lonLat.y) * this.PI / 360)) / (this.PI / 180);
	    y = y * this.a / 180;
	    return {
	        x: x,
	        y: y
	    }
	}
	 
	 /*
	    *Web墨卡托转经纬度
	    *@mercator 平面坐标
	    */
	_.prototype.webMercator2LonLat = function (mercator) {
	    let x = mercator.x / this.a * 180;
	    let y = mercator.y / this.a * 180;
	    y = 180 / this.PI * (2 * (Math.exp(y * this.PI / 180)) - this.PI / 2);
	    return {
	        x: x,
	        y: y
	    }
	}

	_.prototype.get_atan = function (z, y) {
	    let x;
	    if (z == 0) {
	        x = this.PI / 2;
	    } else {
	        if (y == 0) {
	            x = this.PI;
	        } else {
	            x = Math.atan(Math.abs(y / z));
	            if ((y > 0) && (z < 0)) {
	                x = this.PI - x;
	            } else if ((y < 0) && (z < 0)) {
	                x = this.PI + x;
	            } else if ((y < 0) && (z > 0)) {
	                x = 2 * this.M_PI - x;
	            }
	        }
	    }
	    return x;
	}
	//WGS84转ECEF坐标系
	_.prototype.ConvertLLAToXYZ = function (LLACoor) {
	    let lon = this.PI / 180 * LLACoor.longitude;
	    let lat = this.PI / 180 * LLACoor.latitude;
	    let H = LLACoor.altitude;
	    let N0 = this.a / Math.sqrt(1.0 - this.ee * Math.sin(lat) * Math.sin(lat));
	    let x = (N0 + H) * Math.cos(lat) * Math.cos(lon);
	    let y = (N0 + H) * Math.cos(lat) * Math.sin(lon);
	    let z = (N0 * (1.0 - this.ee) + H) * Math.sin(lat);
	    return {
	        x: x,
	        y: y,
	        z: z
	    }
	}

	//ECEF坐标系转WGS84
	_.prototype.ConvertXYZToLLA = function (XYZCoor) {
	    let longitude = this.get_atan(XYZCoor.x, XYZCoor.y);
	    if (longitude < 0) {
	        longitude = longitude + this.PI;
	    }
	    let latitude = this.get_atan(Math.sqrt(XYZCoor.x * XYZCoor.x + XYZCoor.y * XYZCoor.y), XYZCoor.z);

	    let W = Math.sqrt(1 - this.WGSe2 * Math.sin(latitude) * Math.sin(latitude));
	    let N = this.WGSa / W;
	    let B1;
	    do {
	        B1 = latitude;
	        W = Math.sqrt(1 - this.WGSe2 * Math.sin(B1) * Math.sin(B1));
	        N = this.WGSa / W;
	        latitude = this.get_atan(Math.sqrt(XYZCoor.x * XYZCoor.x + XYZCoor.y * XYZCoor.y), (XYZCoor.z + N * this.WGSe2 * Math.sin(B1)));
	    }
	    while (Math.abs(latitude - B1) > this.EPSILON);

	    altitude = Math.sqrt(XYZCoor.x * XYZCoor.x + XYZCoor.y * XYZCoor.y) / Math.cos(latitude) - this.WGSa / Math.sqrt(1 - this.WGSe2 * Math.sin(latitude) * Math.sin(latitude));

	    return {
	        longitude: longitude * 180 / this.PI,
	        latitude: latitude * 180 / this.PI,
	        altitude: altitude
	    }
	}
	/*北东天坐标系转WGS84
	@ a A点坐标
	@ p 相对参数，距离、方位角、仰角
	*/
		//	俯视角pitch -elevation 
	//航向角heading（yaw） -azimuth 
	_.prototype.enu_to_ecef = function (a, p) {
	    //距离
	    let distance = p.distance;
	    //方位角
	    let azimuth = p.azimuth;
	    //仰角
	    let elevation = p.elevation;

	    let zUp = elevation >= 0 ? distance * Math.sin(this.PI / 180 * elevation) : (-1) * distance * Math.sin(this.PI / 180 * Math.abs(elevation));

	    let d = distance * Math.cos(this.PI / 180 * Math.abs(elevation));
	    let xEast;
	    let yNorth;
	    if (azimuth <= 90) {
	        xEast = d * Math.sin(this.PI / 180 * azimuth);
	        yNorth = d * Math.cos(this.PI / 180 * azimuth);
	    } else if (azimuth > 90 && azimuth < 180) {
	        xEast = d * Math.cos(this.PI / 180 * (azimuth - 90));
	        yNorth = (-1)*d * Math.sin(this.PI / 180 * (azimuth - 90));
	    } else if (azimuth > 180 && azimuth < 270) {
	        xEast = (-1) * d * Math.sin(this.PI / 180 * (azimuth - 180));
	        yNorth =(-1) *  d * Math.cos(this.PI / 180 * (azimuth - 180));
	    } else {
	        xEast = (-1) * d * Math.sin(this.PI / 180 * (360 - azimuth));
	        yNorth =  d * Math.cos(this.PI / 180 * (360 - azimuth));
	    }

	    let lamb = this.radians(a.latitude);
	    let phi = this.radians(a.longitude);
	    let h0 = a.altitude;

	    let s = Math.sin(lamb);
	    let N = this.a / Math.sqrt(1.0 - this.e_sq * s * s);

	    let sin_lambda = Math.sin(lamb);
	    let cos_lambda = Math.cos(lamb);

	    let sin_phi = Math.sin(phi);
	    let cos_phi = Math.cos(phi);

	    let x0 = (h0 + N) * cos_lambda * cos_phi;
	    let y0 = (h0 + N) * cos_lambda * sin_phi;
	    let z0 = (h0 + (1 - this.e_sq) * N) * sin_lambda;

	    let t = cos_lambda * zUp - sin_lambda * yNorth;

	    let zd = sin_lambda * zUp + cos_lambda * yNorth;
	    let xd = cos_phi * t - sin_phi * xEast;
	    let yd = sin_phi * t + cos_phi * xEast;

	    return this.ConvertXYZToLLA({
	        x: xd + x0,
	        y: yd + y0,
	        z: zd + z0
	    })
	}
	_.prototype.radians = function (degree) {
	    return this.PI / 180 * degree;
	}	 
	cesium.ECEF = _;
})

;
///<jscompress sourcefile="VFGDraw.js" />
VFG.Draw = function() {
}

//绘制点
VFG.Draw.Point=function(viewer,option){
	this.option=option;
	this.viewer=viewer;
	this.entity;
	this.cesiumTips=new Cesium.Tip(this.viewer);
	this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
	this.init();
	return this;
}

VFG.Draw.Point.prototype.init=function(){
	var _this=this;
	var position;
	_this.handler.setInputAction(function (movement) {
        var cartesian3 =VFG.Util.getScreenToC3(_this.viewer,movement.position,_this.entity);
        if (Cesium.defined(cartesian3)){
        	position=cartesian3;
        	 if(!Cesium.defined(_this.entity)){
             	_this.entity =_this.viewer.entities.add({
            		id:VFG.Util.getUuid(),
            		position: new Cesium.CallbackProperty(function () {
        	            return position;
        	        }, false),
                    point: {
                        color: Cesium.Color.RED,
                        pixelSize: 5,
                        outline: true,
                        outlineColor: Cesium.Color.YELLOW.withAlpha(1),
                    	outlineWidth:1,
                    }
                });
        	 }
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
	
	_this.handler.setInputAction(function (movement) {
        if(Cesium.defined(_this.entity)){
        	_this.cesiumTips.showAt(movement.endPosition, `<div class="con" style="color: white;">单击更新位置，右键结束！</div>`);
        }else{
    		_this.cesiumTips.showAt(movement.endPosition, `<div class="con" style="color: white;">单击添加点，右键结束！</div>`);
    	}
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	
    //右键点击操作
	_this.handler.setInputAction(function (click) {
    	if(_this.option && _this.option.finish){
    		 _this.option.finish(VFG.Util.getLnLaFormC3(_this.viewer,position));
    	}
    	_this.destroy();
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
}

VFG.Draw.Point.prototype.destroy=function(){
    if( this.handler){
    	this.handler.destroy();
    	this.handler = null;
    };
    if(Cesium.defined(this.entity)){
    	this.viewer.entities.remove(this.entity);
    }
    if( this.cesiumTips){
    	this.cesiumTips.destroy();
    	this.cesiumTips=null;
    };
    delete this.viewer,
    delete this.entity,
	delete this.cesiumTips,
	delete this.handler;
	return Cesium.destroyObject(this);
}


//绘制折线
VFG.Draw.Polyline=function(viewer,option){
	this.option=option;
	this.viewer=viewer;
	this.entity;
	this.cesiumTips=new Cesium.Tip(this.viewer);
	this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
	this.init();
	return this;
}

VFG.Draw.Polyline.prototype.init=function(){
	var _this=this;
	var positions= [];
	_this.handler.setInputAction(function (movement) {
        var cartesian3 =VFG.Util.getScreenToC3(_this.viewer,movement.position,_this.entity);
        if (Cesium.defined(cartesian3)){
            if (positions.length == 0) {
            	positions.push(cartesian3.clone());
            }
            positions.push(cartesian3);
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
	
	_this.handler.setInputAction(function (movement) {
    	var cartesian3 =VFG.Util.getScreenToC3(_this.viewer,movement.endPosition,_this.entity);
        if(Cesium.defined(cartesian3)){
        	positions.pop();
        	positions.push(cartesian3);
        }
        if (positions.length >= 2 && !Cesium.defined(_this.entity)){
        	_this.entity =_this.viewer.entities.add({
        		id:VFG.Util.getUuid(),
                polyline: {
                    positions: new Cesium.CallbackProperty(function () {
        	            return positions;
        	        }, false),
                    width: 3.0,
                    clampToGround: true,
                    material:  Cesium.Color.RED,
                }
            });
        }
    	if (positions.length > 1){
    		_this.cesiumTips.showAt(movement.endPosition, `<div class="con" style="color: white;">请绘制下一个点，右键结束！</div>`);
    	}else{
    		_this.cesiumTips.showAt(movement.endPosition, `<div class="con" style="color: white;">左键单击绘制，右键结束绘制！</div>`);
    	}
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	
    //右键点击操作
	_this.handler.setInputAction(function (click) {
    	if(positions){
		  positions.pop();
    	}
    	if(_this.option && _this.option.finish){
    		 _this.option.finish(VFG.Util.c3sToLnLas(_this.viewer,positions));
    	}
    	_this.destroy();
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
}

VFG.Draw.Polyline.prototype.destroy=function(){
    if( this.handler){
    	this.handler.destroy();
    	this.handler = null;
    };
    if(Cesium.defined(this.entity)){
    	this.viewer.entities.remove(this.entity);
    }
    if( this.cesiumTips){
    	this.cesiumTips.destroy();
    	this.cesiumTips=null;
    };
    delete this.viewer,
    delete this.entity,
	delete this.cesiumTips,
	delete this.handler;
	return Cesium.destroyObject(this);
}

//绘制多边形
VFG.Draw.Polygon=function(viewer,option){
	this.option=option;
	this.viewer=viewer;
	this.entity;
	this.cesiumTips=new Cesium.Tip(this.viewer);
	this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
	this.init();
	return this;
}

VFG.Draw.Polygon.prototype.init=function(){
	var _this=this;
	var positions= [];
	_this.handler.setInputAction(function (movement) {
        var cartesian3 =VFG.Util.getScreenToC3(_this.viewer,movement.position,_this.entity);
        if (Cesium.defined(cartesian3)){
            if (positions.length == 0) {
            	positions.push(cartesian3.clone());
            }
            positions.push(cartesian3);
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
	
	_this.handler.setInputAction(function (movement) {
    	var cartesian3 =VFG.Util.getScreenToC3(_this.viewer,movement.endPosition,_this.entity);
        if(Cesium.defined(cartesian3)){
        	positions.pop();
        	positions.push(cartesian3);
        }
        if (positions.length >= 2 && !Cesium.defined(_this.entity)){
        	_this.entity =_this.viewer.entities.add({
        		id:VFG.Util.getUuid(),
//                polygon:{
//                    hierarchy : new Cesium.CallbackProperty(function () {
//        	            return new Cesium.PolygonHierarchy(positions);
//        	        }, false),
//                    perPositionHeight: false,
//                    material: Cesium.Color.RED.withAlpha(0.7),
//                }
                polyline: {
                    positions: new Cesium.CallbackProperty(function () {
        	            return positions;
        	        }, false),
                    width: 2.0,
                   /* clampToGround: false,*/
                    material:  Cesium.Color.RED,
                }
            });
        }
    	if (positions.length > 1){
    		_this.cesiumTips.showAt(movement.endPosition, `<div class="con" style="color: white;">请绘制下一个点，右键结束！</div>`);
    	}else{
    		_this.cesiumTips.showAt(movement.endPosition, `<div class="con" style="color: white;">左键单击绘制，右键结束绘制！</div>`);
    	}
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	
    //右键点击操作
	_this.handler.setInputAction(function (click) {
    	if(positions){
		  positions.pop();
    	}
    	if(_this.option && _this.option.finish){
    		 _this.option.finish(VFG.Util.c3sToLnLas(_this.viewer,positions));
    	}
    	_this.destroy();
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
}

VFG.Draw.Polygon.prototype.destroy=function(){
    if( this.handler){
    	this.handler.destroy();
    	this.handler = null;
    };
    if(Cesium.defined(this.entity)){
    	this.viewer.entities.remove(this.entity);
    }
    if( this.cesiumTips){
    	this.cesiumTips.destroy();
    	this.cesiumTips=null;
    };
    delete this.viewer,
    delete this.entity,
	delete this.cesiumTips,
	delete this.handler;
	return Cesium.destroyObject(this);
}

//绘制画圆
VFG.Draw.Circle=function(viewer,option){
	this.option=option;
	this.viewer=viewer;
	this.entity;
	this.cesiumTips=new Cesium.Tip(this.viewer);
	this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
	this.init();
	return this;
}

VFG.Draw.Circle.prototype.init=function(){
	var _this=this;
	var positions= [];
	var geodesic = new Cesium.EllipsoidGeodesic();
	_this.handler.setInputAction(function (movement) {
        var cartesian3 =VFG.Util.getScreenToC3(_this.viewer,movement.position,_this.entity);
        if (Cesium.defined(cartesian3)){
            if (positions.length == 0) {
            	positions.push(cartesian3.clone());
            }
            positions.push(cartesian3);
        }
        
        if(positions.length>2){
          	if(_this.option && _this.option.finish){
                var satrt = Cesium.Cartographic.fromCartesian(positions[0]);
                var end = Cesium.Cartographic.fromCartesian(positions[positions.length-1]);    
                geodesic.setEndPoints(satrt, end);
          		_this.option.finish({
          			center:VFG.Util.getLnLaFormC3(_this.viewer,positions[0]),
          			radius: geodesic.surfaceDistance.toFixed(3)*1
          		});
          	}
          	_this.destroy();
        }
        
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
	
	_this.handler.setInputAction(function (movement) {
    	var cartesian3 =VFG.Util.getScreenToC3(_this.viewer,movement.endPosition,_this.entity);
        if(Cesium.defined(cartesian3)){
        	positions.pop();
        	positions.push(cartesian3);
        }
        if (positions.length >= 2 && !Cesium.defined(_this.entity)){
        	_this.entity =_this.viewer.entities.add({
        		id:VFG.Util.getUuid(),
        		position:positions[0],
        		point: {
                   color: Cesium.Color.YELLOW,
                   pixelSize: 5,
                },
        		ellipse:{
                	semiMajorAxis:new Cesium.CallbackProperty(function(){
                        var satrt = Cesium.Cartographic.fromCartesian(positions[0]);
                        var end = Cesium.Cartographic.fromCartesian(positions[positions.length-1]);                   
                        geodesic.setEndPoints(satrt, end);
                        return geodesic.surfaceDistance.toFixed(3)*1
                	}, false),
                	semiMinorAxis:new Cesium.CallbackProperty(function(){
                        var satrt = Cesium.Cartographic.fromCartesian(positions[0]);
                        var end = Cesium.Cartographic.fromCartesian(positions[positions.length-1]);                   
                        geodesic.setEndPoints(satrt, end);
                        return geodesic.surfaceDistance.toFixed(3)*1
                	}, false),
                    material: Cesium.Color.RED.withAlpha(0.7),
                    outline: true,
                    outlineColor: Cesium.Color.YELLOW.withAlpha(1),
                    outlineWidth:1,
                }
            });
        }
    	if (positions.length > 1){
    		_this.cesiumTips.showAt(movement.endPosition, `<div class="con" style="color: white;">请绘制下一个点，右键结束！</div>`);
    	}else{
    		_this.cesiumTips.showAt(movement.endPosition, `<div class="con" style="color: white;">左键单击绘制，右键结束绘制！</div>`);
    	}
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	
    //右键点击操作
	_this.handler.setInputAction(function (click) {
    	if(positions){
		  positions.pop();
    	}
    	if(_this.option && _this.option.finish){
    		 _this.option.finish();
    	}
    	_this.destroy();
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
}


VFG.Draw.Circle.prototype.destroy=function(){
    if( this.handler){
    	this.handler.destroy();
    	this.handler = null;
    };
    if(Cesium.defined(this.entity)){
    	this.viewer.entities.remove(this.entity);
    }
    if( this.cesiumTips){
    	this.cesiumTips.destroy();
    	this.cesiumTips=null;
    };
    delete this.viewer,
    delete this.entity,
	delete this.cesiumTips,
	delete this.handler;
	return Cesium.destroyObject(this);
}

//绘制矩形
VFG.Draw.Rectangle=function(viewer,option){
	this.option=option;
	this.viewer=viewer;
	this.entity;
	this.cesiumTips=new Cesium.Tip(this.viewer);
	this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
	this.init();
	return this;
}

VFG.Draw.Rectangle.prototype.init=function(){
	var _this=this;
	var positions= [];
	var geodesic = new Cesium.EllipsoidGeodesic();
	_this.handler.setInputAction(function (movement) {
        var cartesian3 =VFG.Util.getScreenToC3(_this.viewer,movement.position,_this.entity);
        if (Cesium.defined(cartesian3)){
            if (positions.length == 0) {
            	positions.push(cartesian3.clone());
            }
            positions.push(cartesian3);
        }
        
        if(positions.length>2){
          	if(_this.option && _this.option.finish){
                var satrt = Cesium.Cartographic.fromCartesian(positions[0]);
                var end = Cesium.Cartographic.fromCartesian(positions[positions.length-1]);    
                geodesic.setEndPoints(satrt, end);
          		_this.option.finish({
          			center:positions[0],
          			radius: geodesic.surfaceDistance.toFixed(3)*1
          		});
          	}
          	_this.destroy();
        }
        
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
	
	_this.handler.setInputAction(function (movement) {
    	var cartesian3 =VFG.Util.getScreenToC3(_this.viewer,movement.endPosition,_this.entity);
        if(Cesium.defined(cartesian3)){
        	positions.pop();
        	positions.push(cartesian3);
        }
        if (positions.length >= 2 && !Cesium.defined(_this.entity)){
//        	_this.entity =_this.viewer.entities.add({
//        		id:VFG.Util.getUuid(),
//                rectangle:{
//                    coordinates :_self.shape.rect,
//                    material : Cesium.Color.RED.withAlpha(0.4),
//                    height:0,
//                    outline: true,
//                    outlineColor: Cesium.Color.YELLOW.withAlpha(1),
//                    outlineWidth:1,
//                }
//            });
        }
    	if (positions.length > 1){
    		_this.cesiumTips.showAt(movement.endPosition, `<div class="con" style="color: white;">请绘制下一个点，右键结束！</div>`);
    	}else{
    		_this.cesiumTips.showAt(movement.endPosition, `<div class="con" style="color: white;">左键单击绘制，右键结束绘制！</div>`);
    	}
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	
    //右键点击操作
	_this.handler.setInputAction(function (click) {
    	if(positions){
		  positions.pop();
    	}
    	if(_this.option && _this.option.finish){
    		 _this.option.finish();
    	}
    	_this.destroy();
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
}


VFG.Draw.Rectangle.prototype.destroy=function(){
    if( this.handler){
    	this.handler.destroy();
    	this.handler = null;
    };
    if(Cesium.defined(this.entity)){
    	this.viewer.entities.remove(this.entity);
    }
    if( this.cesiumTips){
    	this.cesiumTips.destroy();
    	this.cesiumTips=null;
    };
    delete this.viewer,
    delete this.entity,
	delete this.cesiumTips,
	delete this.handler;
	return Cesium.destroyObject(this);
}


 ;
///<jscompress sourcefile="VFGKml.js" />
VFG.Kml=function(){
}
VFG.Kml.Primitives=new Map();
VFG.Kml.add=function(viewer,options){
	let _this=this;
	if(!this.Primitives.has(options.id)){
	    viewer.dataSources.add(Cesium.KmlDataSource.load(options.url, {
	        camera : viewer.scene.camera,
	        canvas : viewer.scene.canvas,
	        clampToGround:options.clampToGround?options.clampToGround: true //开启贴地
	    })).then(function(dataSource){
	    	console.log(dataSource);
	    });
	}else{
	}
}


;
///<jscompress sourcefile="VFGOrbitControls.js" />
//    		new VFG.OrbitControls(viewer,{
//    			id:VFG.Util.getUuid(),
//    			position:Cesium.Cartesian3.fromDegrees(103.38398032314626,23.368851347473854,1350)
//    		});
VFG.OrbitControls=function(viewer,options){
	this.viewer=viewer;
	this.options=options;
	this.id=options.id;
	this.position=this.options.position;
	this.modelMatrix=Cesium.Transforms.eastNorthUpToFixedFrame(this.options.position);
	this.pickRay = new Cesium.Ray();
	this._init();
}
VFG.OrbitControls.prototype._init = function() {
	var _this=this;
	
    // 向上的向量
    const vectorNormalUp = new Cesium.Cartesian3()
    const vZ = new Cesium.Cartesian3(0, 0, 1)
    Cesium.Cartesian3.normalize(this.position.clone(), vectorNormalUp)

    // 向右的向量
    const vectorNormalRight = new Cesium.Cartesian3()
    // 由z轴向上 地表向上两个向量叉乘, 则可以得出, 向右的向量
    Cesium.Cartesian3.cross(vZ, vectorNormalUp, vectorNormalRight)

    // 向前的向量
    const vectorNormalFront = new Cesium.Cartesian3()
    Cesium.Cartesian3.cross(vectorNormalRight, vectorNormalUp, vectorNormalFront)
    Cesium.Cartesian3.multiplyByScalar(vectorNormalFront, -1, vectorNormalFront)
    
    
    this.axisX = {
        id: 'axisX',
        color: Cesium.Color.GREEN,
        direction: vectorNormalRight,
        unit: Cesium.Cartesian3.UNIT_X,
    }
    this.axisZ ={
        id: 'axisZ',
        color: Cesium.Color.RED,
        direction: vectorNormalUp,
        unit: Cesium.Cartesian3.UNIT_Z,
    }
    this.axisY ={
        id: 'axisY',
        color: Cesium.Color.BLUE,
        direction: vectorNormalFront,
        unit: Cesium.Cartesian3.UNIT_Y,
    }
	
    this._primitiveX=new Cesium.Primitive({
        geometryInstances : new  Cesium.GeometryInstance({
            geometry : new  Cesium.PolylineGeometry({
                positions : [
                	 Cesium.Cartesian3.ZERO,
                	 Cesium.Cartesian3.UNIT_X
                ],
                width :16,
                vertexFormat : Cesium.PolylineMaterialAppearance.VERTEX_FORMAT,
                colors : [
                	 Cesium.Color.RED,
                	 Cesium.Color.RED
                ],
                arcType:  Cesium.ArcType.NONE
            }),
            id:_this.id+"-X", 
            modelMatrix :_this.getModelMatrix(),
            pickPrimitive : this
        }),
        appearance : new Cesium.PolylineMaterialAppearance({
            material : new Cesium.Material({
                fabric : {
                    type : 'PolylineArrow',
                    uniforms : {
                        color :  Cesium.Color.RED
                    }
                }
            })
        })
    })
    
    
    this._primitiveY=new Cesium.Primitive({
        geometryInstances : new  Cesium.GeometryInstance({
            geometry : new  Cesium.PolylineGeometry({
                positions : [
                	Cesium.Cartesian3.ZERO,
                	Cesium.Cartesian3.UNIT_Y
                ],
                width :16,
                vertexFormat : Cesium.PolylineMaterialAppearance.VERTEX_FORMAT,
                colors : [
                	 Cesium.Color.GREEN,
                	 Cesium.Color.GREEN
                ],
                arcType:  Cesium.ArcType.NONE
            }),
            id:_this.id+"-Y",
            modelMatrix :_this.getModelMatrix(),
            pickPrimitive : this
        }),
        appearance : new Cesium.PolylineMaterialAppearance({
            material : new Cesium.Material({
                fabric : {
                    type : 'PolylineArrow',
                    uniforms : {
                        color :  Cesium.Color.GREEN
                    }
                }
            })
        })
    })
    
    this._primitiveZ=new Cesium.Primitive({
        geometryInstances : new  Cesium.GeometryInstance({
            geometry : new  Cesium.PolylineGeometry({
                positions : [
                	 Cesium.Cartesian3.ZERO,
                	 Cesium. Cartesian3.UNIT_Z
                ],
                width :16,
                vertexFormat : Cesium.PolylineMaterialAppearance.VERTEX_FORMAT,
                colors : [
                	 Cesium.Color.BLUE,
                	 Cesium.Color.BLUE
                ],
                arcType:  Cesium.ArcType.NONE
            }),
            id:_this.id+"-Z",
            modelMatrix :_this.getModelMatrix(),
            pickPrimitive : this
        }),
        appearance : new Cesium.PolylineMaterialAppearance({
            material : new Cesium.Material({
                fabric : {
                    type : 'PolylineArrow',
                    uniforms : {
                        color :  Cesium.Color.BLUE
                    }
                }
            })
        })
    })
    
    
    
/*   
    */

	
	this._primitiveXY=new Cesium.Primitive({
        geometryInstances : new Cesium.GeometryInstance({
            geometry : new Cesium.PlaneGeometry({
                vertexFormat : Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
            }),
            modelMatrix : this.getModelMatrixXY(),
            id:_this.id+"-XY",
            pickPrimitive : this,
            attributes : {
                color : Cesium.ColorGeometryInstanceAttribute.fromColor(new Cesium.Color(1.0, 0.0, 0.0, 1.0))
            }
        }),
        appearance : new Cesium.PerInstanceColorAppearance({
            closed: false,
            translucent: false
        })
    })
    
    
    
	this._primitiveXZ=new Cesium.Primitive({
        geometryInstances : new Cesium.GeometryInstance({
            geometry : new Cesium.PlaneGeometry({
                vertexFormat : Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
            }),
            modelMatrix : this.getModelMatrixXZ(),
            id:_this.id+"-XZ",
            pickPrimitive : this,
            attributes : {
                color : Cesium.ColorGeometryInstanceAttribute.fromColor(new Cesium.Color(1.0, 0.0, 0.0, 1.0))
            }
        }),
        appearance : new Cesium.PerInstanceColorAppearance({
            closed: false,
            translucent: false
        })
    })
	
	this._primitiveYZ=new Cesium.Primitive({
        geometryInstances : new Cesium.GeometryInstance({
            geometry : new Cesium.PlaneGeometry({
                vertexFormat : Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
            }),
            modelMatrix : this.getModelMatrixYZ(),
            id:_this.id+"-YZ",
            pickPrimitive : this,
            attributes : {
                color : Cesium.ColorGeometryInstanceAttribute.fromColor(new Cesium.Color(1.0, 0.0, 0.0, 1.0))
            }
        }),
        appearance : new Cesium.PerInstanceColorAppearance({
            closed: false,
            translucent: false
        })
    })

    this.viewer.scene.primitives.add( this._primitiveX );
    this.viewer.scene.primitives.add( this._primitiveY );
    this.viewer.scene.primitives.add( this._primitiveZ );
    this.viewer.scene.primitives.add(this._primitiveXY);
    this.viewer.scene.primitives.add(this._primitiveXZ);
    this.viewer.scene.primitives.add(this._primitiveYZ);
    
	this._handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
	var selectedAxis;
	
	//鼠标左键按下
	this._handler.setInputAction(function(e) {
		var pick = _this.viewer.scene.pick(e.position);
		if (Cesium.defined(pick) && pick.id && (  pick.id==_this.id+"-Z" ||   pick.id==_this.id+"-X" ||  pick.id==_this.id+"-Y" ||  pick.id==_this.id+"-XY" ||  pick.id==_this.id+"-XZ" ||  pick.id==_this.id+"-YZ" )){
			_this.pickPoint = _this.viewer.scene.pickPosition(e.position);
			selectedAxis=pick;
			if(pick.id==_this.id+"-X"){
		 		_this._primitiveX.appearance.material.uniforms.color=Cesium.Color.YELLOW;
		 		_this.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
		 	}
		 	else if(pick.id==_this.id+"-Y"){
		 		_this._primitiveY.appearance.material.uniforms.color=Cesium.Color.YELLOW
		 		_this.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
		 	}
		 	else if(pick.id==_this.id+"-Z"){
		 		_this._primitiveZ.appearance.material.uniforms.color=Cesium.Color.YELLOW
		 		_this.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
		 	}
		 	else if(pick.id==_this.id+"-XY"){
			    var attributes = _this._primitiveXY.getGeometryInstanceAttributes(pick.id);
			    if(attributes){
			    	attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.YELLOW)
			    }
		 		_this.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
		 	}
		 	else if(selectedAxis.id==_this.id+"-XZ"){
			    var attributes = _this._primitiveXZ.getGeometryInstanceAttributes(selectedAxis.id);
			    if(attributes){
			    	attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.YELLOW)
			    }
			    _this.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
		 	}
		 	else if(selectedAxis.id==_this.id+"-YZ"){
			    var attributes = _this._primitiveYZ.getGeometryInstanceAttributes(selectedAxis.id);
			    if(attributes){
			    	attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.YELLOW)
			    }
			    _this.viewer.scene.screenSpaceCameraController.enableRotate = false;//锁定相机
		 	}
		}
	},Cesium.ScreenSpaceEventType.LEFT_DOWN);
    
	//鼠标左键释放
	this._handler.setInputAction(function(e) {
		if(selectedAxis){
		 	if(selectedAxis.id==_this.id+"-X"){
		 		_this._primitiveX.appearance.material.uniforms.color=Cesium.Color.RED;
		 	}
		 	else if(selectedAxis.id==_this.id+"-Y"){
		 		_this._primitiveY.appearance.material.uniforms.color=Cesium.Color.GREEN
		 	}
		 	else if(selectedAxis.id==_this.id+"-Z"){
		 		_this._primitiveZ.appearance.material.uniforms.color=Cesium.Color.BLUE
		 	}
		 	else if(selectedAxis.id==_this.id+"-XY"){
			    var attributes = _this._primitiveXY.getGeometryInstanceAttributes(selectedAxis.id);
			    if(attributes){
			    	attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.RED)
			    }
		 	}
		 	else if(selectedAxis.id==_this.id+"-XZ"){
			    var attributes = _this._primitiveXZ.getGeometryInstanceAttributes(selectedAxis.id);
			    if(attributes){
			    	attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.RED)
			    }
		 	}
		 	else if(selectedAxis.id==_this.id+"-YZ"){
			    var attributes = _this._primitiveYZ.getGeometryInstanceAttributes(selectedAxis.id);
			    if(attributes){
			    	attributes.color =Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.RED)
			    }
		 	}
		 	selectedAxis=null;
	        this.pickPoint = null
		}
		_this.viewer.scene.screenSpaceCameraController.enableRotate = true;//解锁相机
	},Cesium.ScreenSpaceEventType.LEFT_UP);
	
	this._handler.setInputAction(function(movement) {
		if(selectedAxis){
		 	if(selectedAxis.id==_this.id+"-X"){
		 		_this._moveX(movement);
		 	}
		 	else if(selectedAxis.id==_this.id+"-Y"){
		 		_this._moveY(movement);
		 	}
		 	else if(selectedAxis.id==_this.id+"-Z"){
		 		_this._moveZ(movement);
		 	}
		 	else if(selectedAxis.id==_this.id+"-XY"){
		 		_this._precessTranslation2(movement,'XY');
		 	}
		 	else if(selectedAxis.id==_this.id+"-XZ"){
		 		_this._precessTranslation2(movement,'XZ');
		 	}
		 	else if(selectedAxis.id==_this.id+"-YZ"){
		 		_this._precessTranslation2(movement,'YZ');
		 	}
		}
	}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	
	this._handler.setInputAction(function(movement) {
		if(_this.options.end){
			_this.options.end(_this.position);
		}
		_this.destroy();
	}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
	
};


VFG.OrbitControls.prototype.getModelMatrix=function () {
	return Cesium.Matrix4.multiplyByUniformScale(Cesium.Transforms.eastNorthUpToFixedFrame(this.position),100, new Cesium.Matrix4())
}

VFG.OrbitControls.prototype.getModelMatrixXY=function(){
    var dimensions = new Cesium.Cartesian3(1.0, 1.0, 1.0);
    var scaleMatrix = Cesium.Matrix4.fromScale(dimensions);
    var xPlaneMatrix=Cesium.Matrix4.multiply(Cesium.Transforms.eastNorthUpToFixedFrame(this.position), scaleMatrix, new Cesium.Matrix4());
	Cesium.Matrix4.multiplyByTranslation(
		xPlaneMatrix,
        Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.UNIT_X, 0.5, new Cesium.Cartesian3()),
        xPlaneMatrix
    );
	Cesium.Matrix4.multiplyByTranslation(
		xPlaneMatrix,
        Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.UNIT_Y, 0.5, new Cesium.Cartesian3()),
        xPlaneMatrix
    );
	return xPlaneMatrix;
}

VFG.OrbitControls.prototype.getModelMatrixXZ=function(){
    var xPlaneMatrix=this.getModelMatrixXY();
    
    var mx = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(90));
    var rotationX = Cesium.Matrix4.fromRotationTranslation(mx);
    Cesium.Matrix4.multiply(
    		xPlaneMatrix,
            rotationX,
            xPlaneMatrix
    );
    
    Cesium.Matrix4.multiplyByTranslation(
    		xPlaneMatrix,
            Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.UNIT_Z, 0.5, new Cesium.Cartesian3()),
            xPlaneMatrix
        );
    Cesium.Matrix4.multiplyByTranslation(
    		xPlaneMatrix,
            Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.UNIT_Y, 0.5, new Cesium.Cartesian3()),
            xPlaneMatrix
        );
	return xPlaneMatrix;
}

VFG.OrbitControls.prototype.getModelMatrixYZ=function(){
    var xPlaneMatrix=this.getModelMatrixXY();
    
    var mx = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(90));
    var rotationX = Cesium.Matrix4.fromRotationTranslation(mx);
    Cesium.Matrix4.multiply(
    		xPlaneMatrix,
            rotationX,
            xPlaneMatrix
    );
    Cesium.Matrix4.multiplyByTranslation(
    		xPlaneMatrix,
            Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.UNIT_X, -0.5, new Cesium.Cartesian3()),
            xPlaneMatrix
        );
    Cesium.Matrix4.multiplyByTranslation(
    		xPlaneMatrix,
            Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.UNIT_Z, -0.5, new Cesium.Cartesian3()),
            xPlaneMatrix
        );
/*    
    Cesium.Matrix4.multiplyByTranslation(
    		xPlaneMatrix,
            Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.UNIT_Y, 0.5, new Cesium.Cartesian3()),
            xPlaneMatrix
        );*/
	return xPlaneMatrix;
}



/**
 * 处理选中
 * @param e{startPosition: Cesium.Cartesian2, endPosition: Cesium.Cartesian2}}
 * @param axis{ArrowPolyline}
 * @private
 */
VFG.OrbitControls.prototype._precessTranslation=function (e, axis) {

    if (!this.pickPoint) return
    this.viewer.camera.getPickRay(e.startPosition, this.pickRay)
    const startPosition = this.getPlanePosition(this.pickPoint, this.viewer.camera.position.clone(), this.pickRay, axis.direction)
    this.viewer.camera.getPickRay(e.endPosition, this.pickRay)
    const endPosition = this.getPlanePosition(this.pickPoint, this.viewer.camera.position.clone(), this.pickRay, axis.direction)
    const moveVector = new Cesium.Cartesian3()
    Cesium.Cartesian3.subtract(endPosition, startPosition, moveVector)
    const moveLength = -Cesium.Cartesian3.dot(axis.direction, moveVector)
    this.translation(moveVector, axis.unit, moveLength)

}

VFG.OrbitControls.prototype._precessTranslation2=function (e, axis) {
	if (!this.pickPoint) return
	if('XY'==axis){
	   this._moveX(e);
	   this._moveY(e);
	 }
	else if('XZ'==axis){
	   this._moveX(e);
	   this._moveZ(e);
	}else{
	   this._moveY(e);
	   this._moveZ(e);
	}
}

VFG.OrbitControls.prototype._moveX=function (e) {
	if (!this.pickPoint) return
    this.viewer.camera.getPickRay(e.startPosition, this.pickRay)
    const startPosition = this.getPlanePosition(this.pickPoint, this.viewer.camera.position.clone(), this.pickRay, this.axisX.direction)
    this.viewer.camera.getPickRay(e.endPosition, this.pickRay)
    const endPosition = this.getPlanePosition(this.pickPoint, this.viewer.camera.position.clone(), this.pickRay, this.axisX.direction)
    const moveVector = new Cesium.Cartesian3()
    Cesium.Cartesian3.subtract(endPosition, startPosition, moveVector)
    const moveLength = -Cesium.Cartesian3.dot(this.axisX.direction, moveVector)
    this.translation(moveVector,  this.axisX.unit, moveLength)
}

VFG.OrbitControls.prototype._moveY=function (e) {
	if (!this.pickPoint) return
    this.viewer.camera.getPickRay(e.startPosition, this.pickRay)
    const startPosition = this.getPlanePosition(this.pickPoint, this.viewer.camera.position.clone(), this.pickRay, this.axisY.direction)
    this.viewer.camera.getPickRay(e.endPosition, this.pickRay)
    const endPosition = this.getPlanePosition(this.pickPoint, this.viewer.camera.position.clone(), this.pickRay, this.axisY.direction)
    const moveVector = new Cesium.Cartesian3()
    Cesium.Cartesian3.subtract(endPosition, startPosition, moveVector)
    const moveLength = -Cesium.Cartesian3.dot(this.axisY.direction, moveVector)
    this.translation(moveVector,  this.axisY.unit, moveLength)
}

VFG.OrbitControls.prototype._moveZ=function (e) {
	if (!this.pickPoint) return
    this.viewer.camera.getPickRay(e.startPosition, this.pickRay)
    const startPosition = this.getPlanePosition(this.pickPoint, this.viewer.camera.position.clone(), this.pickRay, this.axisZ.direction)
    this.viewer.camera.getPickRay(e.endPosition, this.pickRay)
    const endPosition = this.getPlanePosition(this.pickPoint, this.viewer.camera.position.clone(), this.pickRay, this.axisZ.direction)
    const moveVector = new Cesium.Cartesian3()
    Cesium.Cartesian3.subtract(endPosition, startPosition, moveVector)
    const moveLength = -Cesium.Cartesian3.dot(this.axisZ.direction, moveVector)
    this.translation(moveVector,  this.axisZ.unit, moveLength)
}

/**
 * 获取平面上的位置
 * @param position{Cesium.Cartesian3} 模型位置
 * @param cameraPosition{Cesium.Cartesian3} 相机位置
 * @param pickRay{Cesium.Ray} 从相机到屏幕的射线
 * @param axisDirection{Cesium.Cartesian3} 轴的向量
 */
VFG.OrbitControls.prototype.getPlanePosition =function(position, cameraPosition, pickRay, axisDirection) {
    // 第一步, 获取相机在轴上的投影
    const cartesian3 = Cesium.Cartesian3.subtract(cameraPosition, position, new Cesium.Cartesian3())
    const length = Cesium.Cartesian3.dot(cartesian3, axisDirection)
    // 获取轴上投影的位置, 以相机到这个位置, 为平面法线
    Cesium.Cartesian3.multiplyByScalar(axisDirection, length, cartesian3);
    Cesium.Cartesian3.add(position, cartesian3, cartesian3)
    const pn = Cesium.Cartesian3.subtract(cameraPosition, cartesian3, new Cesium.Cartesian3())
    // 获取单位向量, 射线向投影向量投影
    Cesium.Cartesian3.normalize(pn, cartesian3)
    const number = Cesium.Cartesian3.dot(pickRay.direction, cartesian3)
    // 获取射线与平面相交点
    const number1 = Cesium.Cartesian3.magnitude(pn)
    Cesium.Cartesian3.multiplyByScalar(pickRay.direction, number1/number, cartesian3);
    return cartesian3
}

VFG.OrbitControls.prototype.rayPlaneIntersection=function(ray,cameraDirection,pickPoint){
  if (!pickPoint) {
	  return
  }
  var result = new Cesium.Cartesian3()
  var number = Cesium.Cartesian3.dot(cameraDirection, pickPoint);
  var number1 = Cesium.Cartesian3.dot(cameraDirection, ray.origin);
  var number2 = Cesium.Cartesian3.dot(cameraDirection, ray.direction);
  var t = (number - number1) / number2;
  return Cesium.Cartesian3.add(ray.origin, Cesium.Cartesian3.multiplyByScalar(ray.direction, t, result), result);
}

/**
 * 平移
 * @param moveVector{Cesium.Cartesian3} 移动距离
 * @param unit
 * @param moveLength
 */
VFG.OrbitControls.prototype.translation=function(moveVector, axisUnit, moveLength){
	Cesium.Matrix4.multiplyByTranslation(
        this._primitiveX.modelMatrix,
        Cesium.Cartesian3.multiplyByScalar(axisUnit, moveLength*0.01, new Cesium.Cartesian3()),
        this._primitiveX.modelMatrix
    );
	Cesium.Matrix4.multiplyByTranslation(
        this._primitiveY.modelMatrix,
        Cesium.Cartesian3.multiplyByScalar(axisUnit, moveLength*0.01, new Cesium.Cartesian3()),
        this._primitiveY.modelMatrix
    )
	Cesium.Matrix4.multiplyByTranslation(
        this._primitiveZ.modelMatrix,
        Cesium.Cartesian3.multiplyByScalar(axisUnit, moveLength*0.01, new Cesium.Cartesian3()),
        this._primitiveZ.modelMatrix
    )	
    Cesium.Matrix4.getTranslation(Cesium.Matrix4.multiplyByUniformScale(this._primitiveZ.modelMatrix,1, new Cesium.Matrix4()), this.position);
	
	this._primitiveXY.modelMatrix=this.getModelMatrixXY();
	this._primitiveXZ.modelMatrix=this.getModelMatrixXZ();
	this._primitiveYZ.modelMatrix=this.getModelMatrixYZ();
	if(this.options.callback){
		this.options.callback(this.position);
	}
	
}
VFG.OrbitControls.prototype.getPostition=function (){
	var cartesian3=new Cesium.Cartesian3 ();
	Cesium.Matrix4.getTranslation(this._primitiveZ.modelMatrix,cartesian3);
	return cartesian3
}
VFG.OrbitControls.prototype.destroy = function () {
  if(this._primitiveX){
	  this.viewer.scene.primitives.remove( this._primitiveX );
  }
  if(this._primitiveY){
	  this.viewer.scene.primitives.remove( this._primitiveY );
  }
  if(this._primitiveZ){
	  this.viewer.scene.primitives.remove( this._primitiveZ );
  }
  if(this._primitiveXY){
	  this.viewer.scene.primitives.remove( this._primitiveXY );
  }
  if(this._primitiveXZ){
	  this.viewer.scene.primitives.remove( this._primitiveXZ );
  }
  if(this._primitiveYZ){
	  this.viewer.scene.primitives.remove( this._primitiveYZ );
  }
  delete this.viewer;
  return Cesium.destroyObject(this);
};
;
